For example, I create a class named Circle and define it in Circle.h.
class Circle {
public:
Circle *parent;
Circle();
};
And in a separate Circle.cpp file under the same directory as Circle.h, I define the constructor.
Circle::Circle() {
// creates a root circle, parent is set to itself
*parent = ????
}
What should I fill in the ???? part? In AS3, I know you can use the this keyword to represent the instance itself when defining functions of the class. What do you use in C++?
EDIT 2012/11/29 23:56
There is another constructor:
Circle(Circle*);
Circle::Circle(Circle *cParent) {
*parent = *cParent;
}
And a function, when called, creates a new Circle instance and set the new instance’s *parent to caller.
void addChild();
void Circle::addChild() {
Circle child(????);
}
???? is still that mystery part. According to resources I have read, this seems to be deprecated or has become of other meanings?
The keyword you’re looking for is
this; it’s a pointer to the instance on which the function was invoked. In your example, you’d use it like this:Note that it must be
parent = this;, not*parent = this;. The latter would assign into the objectparentis pointing to, which is not valid (parenthas an indeterminate value). Fortunately, it wouldn’t compile, as you’d be assigning a pointer into an object.For cases such as this (initialising a data member inside a constructor), C++ has the initialiser syntax, which is generally preferred to assigning the members in the constructor body. The code would then look like this: