0

Here's the format of the code:

class C
{
public:
    C();
    virtual ~C() = 0;
};

class D : public C
{
public:
    D();
    ~D();
};

C::C(){
}

C::~C(){
}

D::D(){
}

D::~D(){
}

int main(){
    C *c = new C();
    D *d = new D();
    return 0;
}

When I try to instantiate c I get the following error:

1>c:\main.cpp(59): error C2259: 'C' : cannot instantiate abstract class

I know I cannot call the virtual destructor, but there is something terribly I don't know on the concepts. Can someone explain me?

billz
  • 44,644
  • 9
  • 83
  • 100
Ashwin
  • 1,942
  • 4
  • 30
  • 59
  • 3
    You can't instantiate a class that has a pure virtual method. – Maria Ines Parnisari Dec 13 '12 at 04:06
  • 1
    If you want to instantiate `C`, you shouldn't have any pure functions. Are you sure you need your destructor to be pure? – chris Dec 13 '12 at 04:06
  • Possible duplicate of http://stackoverflow.com/questions/630950/pure-virtual-destructor-in-c?rq=1 – bn. Dec 13 '12 at 04:07
  • @chris, I know about it. What if I have the pure virtual destructor? How can the above problem be solved? – Ashwin Dec 13 '12 at 04:08
  • @Ashwinkumar: The problem is that you both (1) have a pure virtual destructor in your class and (2) are trying to instantiate the class. It can be solved by either (1) *not* having a pure virtual destructor in your class or (2) *not* trying to instantiate it. – ruakh Dec 13 '12 at 04:17

3 Answers3

5

You can't instantiate C because you have explicitly said it's destructor is undefined.

You could just do:

class C
{
public:
    C();
    virtual ~C() {}
};

instead.

You can leave C exactly "as is" as long as you don't try to instantiate it (i.e. you only create Ds, but you can pass them around as Cs.

John3136
  • 28,809
  • 4
  • 51
  • 69
4

“=0” means you define this method as pure virtual. If a class contains any pure virutal method, then the class is pure virtual. You can not instantiate pure virtual class, because there is no implementation for pure virtual method.

TieDad
  • 9,143
  • 5
  • 32
  • 58
2

class C is called abstract class in C++ which can't be initialized.

§10.4/2 Abstract classes An abstract class is a class that can be used only as a base class of some other class; no objects of an abstract class can be created except as subobjects of a class derived from it. A class is abstract if it has at least one pure virtual function.

change C *c = new C(); to C *c = new D(); should work.

Or you can make class C non-abstract class by removing =0

class C{
public:
  C() {}
  virtual ~C() {}
};

C* c = new C();  // this is ok
Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
billz
  • 44,644
  • 9
  • 83
  • 100