Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use 'this' pointer inside constructor [duplicate]

Tags:

c++

class

Possible Duplicate:
C++ using this pointer in constructors

Like the title, may I do something like the following code?

class A;

class B {
public:
    B(A* p);
    ...
};

class A {
    B m;
public:
    A():m(this){}
    ~A(){}
};
like image 818
cHiWa Avatar asked Aug 22 '12 10:08

cHiWa


People also ask

What will happen if a copy constructor?

1. The copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. 2. Copy constructor takes a reference to an object of the same class as an argument.

Can we use for loop inside constructor?

A for loop is an executable control structure. In C#, you can place executable control structures within methods in a class (or in a struct), including within the class's constructor(s) and finalizer, if any.

Can a copy constructor have multiple arguments?

A copy constructor has as its first parameter a (possibly const or volatile) reference to its own class type. It can have more arguments, but the rest must have default values associated with them.

Which is correct for copy constructor?

Explanation: Whenever the compiler creates a temporary object, copy constructor is used to copy the values from existing object to the temporary object. Explanation: While using explicit copy constructor, the pointers of copied object point to the intended memory location.


1 Answers

Yes, you can passed a pointer to an object currently under construction. But you have to keep in mind, that the object isn't constructed completely yet. So basically what B can do in it's c'tor is store the pointer for later use.

An example where this is often used, is a std::stream and a stream buffer.

like image 153
Torsten Robitzki Avatar answered Oct 26 '22 23:10

Torsten Robitzki