I want to have an instance of a class used within its own class definition. Such as:
class A{
private:
A a;
public:
A GetA(){return a;}
};
This is a simple thing to do in java with its mighty multipass compiling, but how could I achieve this in C++?
Printable View
I want to have an instance of a class used within its own class definition. Such as:
class A{
private:
A a;
public:
A GetA(){return a;}
};
This is a simple thing to do in java with its mighty multipass compiling, but how could I achieve this in C++?
First, it's not because of the multipass compilation so much as the means by which objects are created in Java.
In C++, this is done with pointers. I'd suggest smart pointers (they operate something like Java's use of variables).
First of all thanks for bringing up this question, I didn't even realize this wasn't possible.
As Jvene suggested, I was so used to declaring "a" as a pointer to the class "A" in such cases.
Question
-----------
Just wonder why C++ permits the declaration of a pointer to the same class while not an object of the class.
Ah yes, good point. I've actually realised that this isn't the issue that I'm having. I have two classes, each in their own header files. A uses B in its definition and B wants to use A in its definition. It seems the resolution for this is to have a dummy B class defined before A. So nevermind, thanks for your help.
because a pointer has a fixed size, 32 bits on a 32 bit machine and 64 bits on a 64 bit machine, whereas a full blown object has indeterminate size until the full declaration is seen.
Thanks Russco, I didn't know that. I think I understand better.
I don't think forward declaration might help in this case, correct me if I am wrong,
Forward declaration wouldn't solve the problem of incomplete type,
As Russco stated Objects would require the complete class specification, and for pointers forward declaration would be sufficient.
I have given below an example:
Compilation Error:Code:class ClassB;
class ClassA
{
public:
ClassB objB;
};
class ClassB
{
public:
ClassA objA;
};
int main()
{
return(0);
}
Code:test.cpp:6: error: field 'objB' has incomplete type
You're right. Plus even if this was allowed, its meaning would be rather "interesting": a class A object owns a class A object which owns a class A object which...Quote:
Originally Posted by Muthuveerappan