VettelS
VettelS

Reputation: 1224

Template parent class method call

My situation looks something like this:

template<typename T>
class BaseClass1
{
public:
    virtual void foo() = 0;
};

class ChildClass1 : public BaseClass1<int>
{
public:
    void foo() override
    {
        // do stuff
    };
};

template<typename T>
class BaseClass2 : public BaseClass1<T>
{
public:
    virtual void foo() = 0;
};

class ChildClass2 : BaseClass2<int>
{
public:
    void foo() override
    {
        // call ChildClass1::foo()
        BaseClass1::foo();
    };
};

My ultimate aim is to be able to call ChildClass1::foo() inside ChildClass2::foo(), but I'm clearly doing something wrong. All of these classes are defined in their own header files, along with all their method definitions.

Then I have a file where I'm trying to instantiate ChildClass2. It looks something like this:

#include "ChildClass1.hpp"
#include "ChildClass2.hpp"

ChildClass2 obj;
obj.foo();

When I attempt to compile, I get a link error:

[...] unresolved external symbol "public: virtual void __thiscall BaseClass1::foo(void)" [...] referenced in function "public: virtual void __thiscall ChildClass2::foo(void)"

Can anyone tell me what I'm doing wrong here, and/or a better way to achieve my aim if I'm going about it in the wrong way? Also, a more descriptive title would probably be good if anyone can think of one! Thanks.

Upvotes: 0

Views: 97

Answers (2)

swang
swang

Reputation: 5249

I don't think your code can do what you wanted. First you can't call BaseClass1::foo() in ChildClass2::foo(), because BaseClass1::foo() is a pure virtual function.

Second, your ChildClass2 is a child of BaseClass1, the same as ChildClass1, so the two classes have no parent-child relationship, you can't call one's function without a object of that class.

Upvotes: 0

cassandracomar
cassandracomar

Reputation: 1519

Your ChildClass2::foo method calls BaseClass1::foo which isn't defined. Either provide a definition for BaseClass1::foo or don't reference it in ChildClass2::foo and you shouldn't run into this issue.

Upvotes: -1

Related Questions