how to create a object of child class in parent class

Aug 6, 2008 at 5:28am
Hi ,
i am facing a problem , i want to create a object of child class in parent class , as java allows ...what is the way to implement the same is c++ ?

Java code :

class A
{
public void add() {
B b = new B();
b.print();
}
}

class B extends A{
void print() {
System.out.println("In Class B");
}
}

class C {
public static void main(String []arf) {
A a = new A();
a.add();
}
}
Aug 6, 2008 at 5:35am
Umm, your actually allowed to do that? Using your example, I don't really see the point of extending it. OK, so you called a.add(), then you can call a.b.add() and then a.b.b.add() and then a.b.b.b.add()? I don't really see a point >.<

All I know is if B extends A, B should pass the IS-A test.

Is B IS-A A true? If not it shouldn't extend it.
Aug 6, 2008 at 6:04am
I... think it's possible... As long as you don't get an endless recursion (for example, by creating a B inside the constructor for A, since the constructor for B first calls the constructor for A, I think) it is possible. Although something tells me you're doing it wrong if you actually need to do that. You're one step away from dividing by zero.
Aug 6, 2008 at 6:41am
All I could think of are examples from a book on Java I was reading.

If Dog IS-A Canine, Dog should extend Canine. If Dog HAS-A Bark ability, Dog should have a Bark() method. So what I get from your example is, you want Canine to be able to make Dog objects. So Canine HAS-A ability to spawn Dogs lol?
Aug 6, 2008 at 7:56pm
You can do it in C++, but you need to use forward-declaration :)

Edit: However, this maybe evidence of a bad design because you open up the possibility of an infinite allocation loop.
Last edited on Aug 6, 2008 at 8:00pm
Aug 15, 2008 at 11:53pm
thats just bad design, never should a base class depend on it´s dependant, because, as you red, it´s a circular dependency graph
Topic archived. No new replies allowed.