开发者

Cannot instantiate abstract class in C++ error

开发者 https://www.devze.com 2023-04-09 15:52 出处:网络
I want to implement an interface inside a \"Dog\" class, but I\'m getting the following error. The final goal is to use a function that recieves a comparable object so it can compare the actual instan

I want to implement an interface inside a "Dog" class, but I'm getting the following error. The final goal is to use a function that recieves a comparable object so it can compare the actual instance of the object to the one I'm passing by parameter, just like an equals. An Operator overload is not an开发者_JAVA百科 option cause I have to implement that interface. The error triggers when creating the object using the "new" keyword.

" Error 2 error C2259: 'Dog' : cannot instantiate abstract class c:\users\fenix\documents\visual studio 2008\projects\interface-test\interface-test\interface-test.cpp 8 "

Here is the code of the classes involved:

#pragma once

class IComp
{
    public:
        virtual bool f(const IComp& ic)=0; //pure virtual function
};

    #include "IComp.h"
class Dog  : public IComp
{
    public:
        Dog(void);
        ~Dog(void);
        bool f(const Dog& d);
};

#include "StdAfx.h"
#include "Dog.h"

Dog::Dog(void)
{
}

Dog::~Dog(void)
{
}

bool Dog::f(const Dog &d)
{
    return true;
    }

#include "stdafx.h"
#include <iostream>
#include "Dog.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    Dog *d = new Dog; //--------------ERROR HERE**

    system("pause");
        return 0;
}


bool f(const Dog &d) is not an implementation of bool f(const IComp& ic), so the virtual bool f(const IComp& ic) still isn't implemented by Dog


Your class Dog does not implement the method f, because they have different signatures. It needs to be declared as: bool f(const IComp& d); also in the Dog class, since bool f(const Dog& d); is another method altogether.


    bool f(const Dog& d);

is not an implementation for IComp's

    virtual bool f(const IComp& ic)=0; //pure virtual function

Your definition of Dog's f is actually hidding the pure virtual function, instead of implementing it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号