Reputation: 35
How can I fix this code? The error that I'm getting is "undefined reference to 'vtable for base' " The doSomething function should be pure if possible.
Example:
class A{
};
class A_A : public A{
};
class A_B : public A{
};
class A_C : public A{
};
/////////////////////////////////////
class base{
public:
virtual void doSomething(A* );
//virtual void doSomething(A* ) = 0; //or...
};
class derived : public base{
public:
void doSomething(A_A* );
void doSomething(A_B* );
void doSomething(A_C* );
};
Upvotes: 0
Views: 176
Reputation: 3197
By adding the =0
at the back you are forcing the derived class to override the function. This solves the issue:
class base{
public:
virtual void doSomething(A*a) = 0;
};
class derived : public base{
public:
// you can pass any derived class of A to this function
// mark as override suggested by Omid CompSCI for clarity
void doSomething(A*a) override { }
};
I hope that this helps. Also you shouldn't create 3 different versions of doSomething for each of the derived classes of A because this defeats the purpose of having all those classes inherit from A.
Also consider using smart pointers because they will handle memory dealocation for you. Check out this question. This is how I would approach this:
#include<iostream>
#include<memory>
class A
{
public:
virtual void print() = 0;
};
class A1: public A
{
public:
void print() override {std::cout << "A1" << std::endl;}
};
class A2: public A
{
public:
void print() override {std::cout << "A2" << std::endl;}
};
class A3: public A
{
public:
void print() override {std::cout << "A3" << std::endl;}
};
class base
{
public:
virtual void action(std::shared_ptr<A>) = 0;
};
class derived: public base
{
public:
// this way you can have a generic function which will handle each one of the derived classes of A.
void action(std::shared_ptr<A> a) override { a->print(); }
};
Upvotes: 1