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();
}
}
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.
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.
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?