Construct Foo with Method called from constructor.
Author |
Message |
copthesaint

|
Posted: Tue Nov 06, 2012 8:06 pm Post subject: Construct Foo with Method called from constructor. |
|
|
Hi, In C++ I want to know how I may accomplish calling the variable that is using the constructor of a class for eg:
code: | class Foo{
public:
Foo();
};
void InitFoo (Foo& fooPointer){
//init fooPointer
}
Foo::Foo (){
InitFoo (this);
} |
I think some people may find this pointless, but I am just wondering how to be able to do this in C++. |
|
|
|
|
 |
Sponsor Sponsor

|
|
 |
Insectoid

|
Posted: Tue Nov 06, 2012 8:44 pm Post subject: RE:Construct Foo with Method called from constructor. |
|
|
As far as I know, you would use the -> operator to access the properties of fooPointer inside InitFoo(). You won't be able to access private properties though.
Why do you want to do this? Because, well, it does look rather pointless, as you say. |
|
|
|
|
 |
DemonWasp
|
Posted: Tue Nov 06, 2012 9:18 pm Post subject: RE:Construct Foo with Method called from constructor. |
|
|
First, this is either const Type* or const Type* const depending on whether the context is a const method or not, so you can't pass this as Type&.
You can pass it by dereferencing it: InitFoo(*this).
In this particular instance, you're doing something completely pointless. While it is occasionally useful to convert this into a reference, this is a silly usage. You should use one of these techniques:
A) If you are using C++11, use constructor chaining, like every other language: http://en.wikipedia.org/wiki/C%2B%2B0x#Object_construction_improvement
B) If you are not using C++11, start using C++11.
C) If you really can't use C++11, write a private internal method to initialize this object (shouldn't need this as an argument, as it will receive this automatically), and call it from the constructors (see the link above for details). |
|
|
|
|
 |
|
|