| 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.