abstract class - enforce cannot instantiate

C

Christopher

If I have an generic interface, but _also_ have the implementation for
it and want to use that common implementation in my derived classes,
what method does that leave me to make pure virtual such that my
generic interface class cannot be instantiated?

Do you make the destructor virtual?
Do you move constructors to private?

// What do I make pure virtual??
AbstractClass
{
public:

AbstractClass() {}

virtual AbstractClass() {}

virtual void Foo()
{
std::cout << "Foo!" << std::endl;
}
};


DerivedClass : public AbstractClass
{
public:

DerivedClass() {}

~DerivedClass() {}

void Bar()
{
std::cout << "Bar!" <<std::endl;
}
};


I don't want anyone to be able to:
AbstractClass * abstract = new AbstractClass();

I do want people to be able to:
AbstractClass * abstract = new DerivedClass();
abstract->Foo();

and expect:
"Foo!"
 
D

David Côme

If I have an generic interface, but _also_ have the implementation for
it and want to use that common implementation in my derived classes,
what method does that leave me to make pure virtual such that my
generic interface class cannot be instantiated?

Do you make the destructor virtual?
Do you move constructors to private?

// What do I make pure virtual??
AbstractClass
{
public:

AbstractClass() {}

virtual AbstractClass() {}

virtual void Foo()
{
std::cout << "Foo!" << std::endl;
}
};


DerivedClass : public AbstractClass
{
public:

DerivedClass() {}

~DerivedClass() {}

void Bar()
{
std::cout << "Bar!" <<std::endl;
}
};


I don't want anyone to be able to:
AbstractClass * abstract = new AbstractClass();

I do want people to be able to:
AbstractClass * abstract = new DerivedClass();
abstract->Foo();

and expect:
"Foo!"


class AbstractClass
{
public:

AbstractClass() {}

virtual ~AbstractClass()=0;
virtual void Foo()
{
std::cout << "Foo!" << std::endl;
}
};

AbstractClass::~AbstractClass()
{
std::cout<<"Dest ABC"<<std::endl;
}

With this code, AbstractClass's destructor is virtual pure and well
defined.
Try to instanciate an obbject of type AbstractClass, and you will get an
error.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top