Zoran
Zoran

Reputation: 459

abstract base class extension

Here is my simplified code which requires your valuable comments about poorly implemented polymorphism.

class X
{
    public:
        void test();
    protected:
        virtual void foo() const = 0;
};


class Y : public X
{
    public:
        void foo(){ cout << "hello" << endl; }
};


int main()
{   
    X *obj = new Y();
} 

I get the following error at compilation.

test.cpp: In function ‘int main()’:
test.cpp:23: error: cannot allocate an object of abstract type ‘Y’
test.cpp:14: note:   because the following virtual functions are pure within ‘Y’:
test.cpp:9: note:   virtual void X::foo() const

Upvotes: 0

Views: 57

Answers (3)

john
john

Reputation: 88092

Should be

class Y : public X
{
    public:
        void foo() const { cout << "hello" << endl; }
};

Because

void foo() const

and

void foo()

are not the same function.

Upvotes: 4

billz
billz

Reputation: 45470

foo funciton in class Y has different signature with X::foo

class Y : public X
{
  public:
    void foo() const { cout << "hello" << endl; }
};

Upvotes: 2

John3136
John3136

Reputation: 29266

foo in class Y is not const, so you are not overloading the virtual in class X.

Upvotes: 1

Related Questions