user1855338
user1855338

Reputation:

Reusing base class pointer in derived class

Consider the following code:

Class A
{
   int a;
   somepointer* b;
}
Class B : A
{
   void func()
}
main()
{
   A* a1 = new A();
   a1->a = 5;
   a1->b = new somepointer();
   B* b1 = new B()
}

Now when B is created it contains A, I want to reuse the a1 created earlier, that is b1->a should give the value 5.How can this be done?

Upvotes: 0

Views: 91

Answers (2)

Krypton
Krypton

Reputation: 3325

I guess you are providing just prototype of what you want. So I will ignore about the syntax problems.

You can create a constructor in class B that take a variable of type A as parameter:

class B:A {
public:
    B(A *my_a) {
        a = my_a->a;
        b = my_a->b;
    }

    void func() {
        //......
    }
}


main() {
    A *a1 = new A();
    a1->a = 5;
    a1->b = new somepointer();
    b = new B(a);
}

You may think about dynamic casting as well: C++ cast to derived class . But unfortunately that doesn't work, so best way here is to have a constructor so that you can manually set the variables you need for reusing.

Edit: Since Humayara Nazneen wants to have effects that changing a1->b will not affect b->b, then A::b shouldn't be declared as pointer, which means that:

class A {
   int a;
   somepointer b;
}

When you assign b = my_a->b; it will be copied by value.

Upvotes: 1

Felix Glas
Felix Glas

Reputation: 15524

Every instance has its own variables. You can't access a1's members from b1.

Your code have many problems, and the general approach of using pointers like you do does not fit C++ (it looks more like Java).

I suggest you get a good book about C++ and start over. Learning C++ by trial and error is not the best approach.

Upvotes: 1

Related Questions