Initializing member with derived class

Hello, I have a program where I am trying to initialize member with derived class instead of base class, short example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Parent {
public:
    Parent();
    void test_func();
};

class Child: public Parent {
public:
    Child(int child_member);
    void test_func();
private:
    int child_member;
};

class A {
public:
    A(int another_member, bool init_derived);
    void a_test();
private:
    std::unique_ptr<Parent> m;
    int another_member;
};

//inside A.cpp
A::A(int another_member, bool init_derived): another_member(another_member) {
    if (init_derived) {
        m = std::make_unique<Child>(30);
    }
}

A::a_test() {
   // even if init_derived was true, only Parent's test_func get's called here
   m->test_func();
}



So basically I am trying to sometimes init the Child class instead of parent, and use the `test_func` of Child class, but I've not been successful.

Is it possible to initialize a member with a derived class instead of parent class, when some condition is met similiar to this? Or how should I approach this issue please, thank you.
Last edited on
Parent's test_func needs to be virtual.
Topic archived. No new replies allowed.