1

There is a homework question which asks what construct in C++ is similar to a Java interface. An interface in Java can be referred to as a pure abstract class, and I know that C++ has abstract classes, but are pure abstract classes something that C++ officially has?

Maybe from a C++ designer's viewpoint it doesn't, but technically it is possible to create an pure abstract class in C++ by making all methods abstract right?

I looked at this resource but I'm still confused after reading some of the answers...

Community
  • 1
  • 1
maregor
  • 777
  • 9
  • 32
  • 1
    C++ doesn't enforce any particular style of programming, you can do procedures, or OOP, or templates. It also *allows* you to create an interface with only pure virtual functions, but it doesn't force you to. You can also use multiple inheritance with non-pure base classes - your choice! – Bo Persson Nov 09 '15 at 21:01

2 Answers2

4
class Foo {
public:
    Foo();
    virtual ~Foo() {};
    virtual void bar() = 0;
}

Foo is a pure abstract class in C++ because it contains the method bar() which is a pure virtual method.

jayant
  • 2,349
  • 1
  • 19
  • 27
  • 1
    You should use virtual destructor as well – Artur Pyszczuk Nov 09 '15 at 20:57
  • I don't know C++ very well, so one question here; are the constructor and destructor declarations really compulsory here, given that the class has no state? Doesn't C++ fill those by default? Since I do Java, the rules are of course different, but I'd like to know... – fge Nov 09 '15 at 21:12
  • @fge In C++ the base constructor and destructor are called when the derived class's constructor destructor are called. Your code will probably compile and run without the constructor and destructor. But to avoid going to undefined territory you must have a virtual destructor at least. As was pointed out to me when I answered this question and forgot to declare the destructor virtual ;) See [this answer](http://stackoverflow.com/a/461224/1517864) about virtual destructors. – jayant Nov 09 '15 at 21:24
  • 1
    @fge C++ will make a simple constructor and destructor; however, we need to declare our own destructor for an interface because we need it to be pure virtual (note in this example it is not pure virtual, but it should be). The constructor declaration is unnecessary: this class can't ever be constructed, and interfaces often don't have members to construct. The simplest interface would thus be: `class Simple { virtual ~Simple() = 0 {} };` – Tas Nov 09 '15 at 21:25
  • Constructor declaration isn't necessary. – πάντα ῥεῖ Nov 09 '15 at 21:34
  • @πάνταῥεῖ, it is if the 'abstract' class has state. – GreatAndPowerfulOz Nov 09 '15 at 22:24
3

Yes you can create an abstract class in c++

class A {

public:
    A() {};
    virtual ~A(){};
    virtual void temp() = 0;
};

int main () {
    A a; // compiler error
}
owacoder
  • 4,815
  • 20
  • 47
KostasRim
  • 2,053
  • 1
  • 16
  • 32