Link to home
Start Free TrialLog in
Avatar of LuckyLucks
LuckyLucks

asked on

assigning a child class its parent

Hi

I have a class hierarchy as follows:
A (parent)->B(child)


I create an object A. A a=new A();

Somewhere, later in the code, I want to create an object B, called b, and want to specifically assign the object a as its parent. Is there a way to do this in C++?

Normally, I would do something like this:
B b=new B();

B's constructor would make a call to A's constructor
B::B()
:A(){
}

But if i have a parent object already instantiated, is there a way to assign that particular object as a child object's parent at the time the child is instantiated?

thanks
Avatar of jkr
jkr
Flag of Germany image

There seems to be a misconception. A statement like

B::B()
:A(){
}

Open in new window


only a base class' constructor. That is not related to storing a reference to a specific instance to the base class. If you want to create a relation between two instances of A and B, pass an instance of A to one of B's constructors, e.g.

class B {

public:

  // default constructor
  B() : parent(A()) {
  }
  // constructor that implicitly takes an instance of 'A'
  B(A& a) : parent(a) {
  }

private:

  A& parent;
};

Open in new window


If you need to have to option to instantiate B without a parent, you have to use pointers, since references can't be 'NULL', e.g. like

class B {

public:

  // default constructor
  B() : parent(NULL) {
  }
  // constructor that implicitly takes an instance of 'A'
  B(A* a) : parent(a) {
  }

private:

  A* parent;
};

Open in new window

Avatar of LuckyLucks
LuckyLucks

ASKER

In the solution you gave, A and B do not have a base class-derived class relationship. B just keeps a member variable of A.


 B cannot use a function defined in A as would be possible using rules of inheritance (searching the parent class when child class does not have that function).

I am looking for a way where B can be a derived class of A , but as A is already instantiated in earlier code, if i can get an association with that particular instance of A.
SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial