Instantiate class with non default constructor

R

Richard

I have two classes ClassA and ClassB.

ClassB has a constructor that has ClassA as it's parameter. How do I make
ClassB as a member object of ClassA so that ClassA (i.e. 'this') is passed
into ClassB on instatiation?
 
J

John Harrison

Richard said:
I have two classes ClassA and ClassB.

ClassB has a constructor that has ClassA as it's parameter. How do I make
ClassB as a member object of ClassA so that ClassA (i.e. 'this') is passed
into ClassB on instatiation?

class ClassA
{
public:
ClassA() : b(this) {}
private:
ClassB b;
};

Some compilers will give you warnings about this code because you are
using the this pointer before the ClassA object is constructed. But
provided you don't try and dereference the pointer in the ClassB
constructor it is OK.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top