can I declare a class variable inside that class method?

J

John Black

Hi,
Suppose I have a class,

class MyClass{
public:
MyClass();
MyClass(MyClass);

int func();
};

Then can I declare a MyClass object inside MyClass::func()?

int MyClass::func(){
MyClass obj;
<......>
}
 
R

Russell Hanneken

John said:
Suppose I have a class,

class MyClass{
public:
MyClass();
MyClass(MyClass);

Suppose you wrote

MyClass x;
MyClass y(x);

Because the copy constructor parameter is passed by value, a copy of x
is made, and the copy is sent to the copy constructor. But to make the
copy, the MyClass copy constructor would have to be invoked. And then
the argument would have to be copied, using the MyClass copy constructor
again. And so on...

The point is, your copy constructor should take a reference, not a copy:

MyClass(MyClass const &);
int func();
};

Then can I declare a MyClass object inside MyClass::func()?

int MyClass::func(){
MyClass obj;
<......>
}

Sure.
 
J

jeffc

John Black said:
Hi,
Suppose I have a class,

class MyClass{
public:
MyClass();
MyClass(MyClass);

int func();
};

Then can I declare a MyClass object inside MyClass::func()?

int MyClass::func(){
MyClass obj;
<......>
}

Yes. Just don't do this :)
int MyClass::func()
{
MyClass obj;
obj.func();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top