"has-a" question

L

Leo

Dear All,

Can I do this:

class MyClass()
{
public:
doStuff();
private:
int iNum;
};

MyClass::doStuff()
{
MyClass obj; //Is this ok? Has a object inside itself?
cout << obj.iNum << endl;
}

Thank you very much.
 
G

GB

Leo said:
Dear All,

Can I do this:

class MyClass()
{
public:
doStuff();
private:
int iNum;
};

MyClass::doStuff()
{
MyClass obj; //Is this ok? Has a object inside itself?
cout << obj.iNum << endl;
}

Thank you very much.

Yes. The object is not however inside itself. It exists only for the
duration of the execution of Myclass::doStuff as a separate object from
the one on which MyClass::doStuff is being called (i.e., *this is one
object, and obj is another independent one.

Gregg
 
P

Peter_Julian

| Dear All,
|
| Can I do this:
|
| class MyClass()
| {
| public:
| doStuff();
| private:
| int iNum;
| };
|
| MyClass::doStuff()
| {
| MyClass obj; //Is this ok? Has a object inside itself?
| cout << obj.iNum << endl;
| }
|
| Thank you very much.
|

That should have been:
#include <iostream>
#include <ostream>

class MyClass
{
int iNum;
public:
void doStuff();
};

void MyClass::doStuff()
{
MyClass obj;
std::cout << obj.iNum << std::endl; // iNum == garbage
}

You won't get what you expect. the private variable iNum is unitialized
since you are generating a local instance of a MyClass object and no
default ctor has been defined that initializes its internals. Hence the
garbage.

Now consider:

#include <iostream>
#include <ostream>

class MyClass
{
int n;
public:
/* ctor */
MyClass() : n(0) { } // default ctor
MyClass(int i) : n(i) { }
/* d~tor */
~MyClass() { }
/* member function */
int getN() const;
};

int MyClass::getN() const
{
return n;
}

int main()
{
MyClass myclass;
std::cout << myclass.getN() << std::endl; // prints 0, not garbage

MyClass myclass2(99);
std::cout << myclass2.getN() << std::endl; // prints 99

return 0;
}

No more garbage.
 

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,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top