Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In general, what you are looking for, is the <code>virtual</code> keyword. In a nutshell <code>virtual</code> declares the intent that <em>this method can be overriden</em>. Note that such a method can still have an implementation- <code>virtual</code> just makes it overrideable. To declare an "abstract method", you can say declare intent of <em>please provide an implementation in the derived class</em> with <code>= 0</code>, as shown below. Such methods are called <em>pure virtual</em> in C++.</p> <p>However, there are some caveats that you should watch out for. As pointed out in a comment below, you were calling <code>method()</code> from within the <code>SuperClass</code> constructor. Unfortunately this is not possible in C++, due to the order in which objects are constructed. </p> <p>In C++ a derived class constructor immediately calls it's superclass constructor before allocating its members or executing the body of the constructor. As such, the members of the base class are constructed first, and the derived class' members are constructed last. Calling a virtual method from a base class will not work as you expect in Java, since the derived class has not been constructed yet, and thus the virtual methods have not been redirected to the derived implementations yet. Hope that makes sense.</p> <p>However, calling <code>method()</code> on a <code>SuperClass</code> object after creation will work as you expect: it would call the virtual function which would output "print".</p> <pre><code>class SuperClass { public: SuperClass() { // cannot call virtual functions from base constructor. } virtual ~SuperClass() { } // destructor. as Kerrek mentions, // classes that will be inherited from, // should always have virtual destructors. // This allows the destructors of derived classes // to be called when the base is destroyed. private: void method() { unimplementedMethod(); } protected: virtual void unimplementedMethod() = 0; // makes method pure virtual, // to be implemented in subclass } </code></pre> <p>SubClass.h</p> <pre><code>class SubClass : public SuperClass { public: SubClass() : SuperClass() { // how the superclass constructor is called. } // no need for "override" keyword, if the methd has the same name, it will // automatically override that method from the superclass protected: void unimplementedMethod() { std::cout &lt;&lt; "print" &lt;&lt; std::endl; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload