C++ abstract classes

I am new to C++, I coded in Java for an year. The equivalent in C++ for interfaces and abstract classes alike is only abstract classes. Is that supposed to be a handicap while doing factory design? There are many times I want to leave out the defining the methods to the inheriting classes and I want to enforce that.


Java interfaces are best translated as C++ abstract classes. In Java (as far as I know) a interface is merely a subset of an abstract class anyway, except it allows "multiple inheritance" which C++ has in all cases anyway.

class thing_interface {
    virtual ~thing_interface() {}
    virtual void foo() =0; //pure virtual function
class other_interface {
    virtual ~other_interface () {}
    virtual void bar() =0; //pure virtual function

class thing_impl : public thing_interface, public other_interface { 
    int member;
    thing_impl() : member(0) {}
    virtual ~thing_impl() {};
    virtual void foo() { std::cout << "FOO!\n";}
    virtual void bar() { std::cout << "BAR!\n";}

The =0 syntax means it is not defined in the interface, but must be defined in classes that fulfill the interface. Also note that if you have any virtual function, you almost always want a virtual destructor as well. C++ will tell you an error if you try to make a thing_interface by itself, since there's no implementation functions.

It's not really a handicap, since I can't think of anything Java can do here that C++ can't.

If you define like this you can have what you want:

class A {
    virtual void pure_virtual(int param1) = 0;
    virtual ~A() { };

EDIT: Thanks Nikolai and Mike!

Need Your Help

Strange thread behavior with onClickListener

android multithreading view

I am trying to change the background of a button to 'pressed' for 1 second, then change that background back to 'default'. I created one Thread called sleeper that simply sleeps for 1 second. Below...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.