Public Group

# Defining a pure virtual function

This topic is 4916 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I know that to define a pure virtual function you do this virtual void function() = 0; but, is it possible to declare a pure virtual function, and also define it for the base class? (although, that would probably stop it being pure virtual, technically) Basically, I want to know if I can define a function for the base class and also somehow let the compiler and user know that this same function also has to be defined for any derived classes, because they both will be used.

##### Share on other sites
No you can't.

A method is either pure virtual ( must be defined in final interfaces ) or virtual ( could be redefined in final interfaces ) ...

I understand what you seek, the solution is to derive a class call base_ex for example and define the pure methods. and this way all derived classes of base will need to define the pure ones...

ps. of course derived classes can still not define pure virtual methods, but this will prevent instantiation.

##### Share on other sites
Quote:
 Original post by Dee GodNo you can't.A method is either pure virtual ( must be defined in final interfaces ) or virtual ( could be redefined in final interfaces ) ...I understand what you seek, the solution is to derive a class call base_ex for example and define the pure methods. and this way all derived classes of base will need to define the pure ones...ps. of course derived classes can still not define pure virtual methods, but this will prevent instantiation.

Heh, this use to get me in the past, its a complete myth! actually you can provide default implementation for a pure virtual member functions, it just means that sub-type musts override it but they can use the default imp if they wish e.g.:

#include <iostream>struct foo {   virtual void do_bar() const = 0;   virtual ~foo() {}};void foo::do_bar() const { std::cout << "hello\n"; }struct bar : foo { //bar must override foo::do_bar.   void do_bar() const { foo::do_bar(); }};int main() {   foo* foobar = new bar;   foobar->do_bar();   //...   delete foobar;}

And good reasons for doing so.

##### Share on other sites
(extending what snk_kid said, which is the answer to your question [smile])
not only can you define a pure virtual method, but if a destructor is made pure virtual then it must be defined.
struct foo {   virtual ~foo() =0;};
will give you a linker error if you instantiate an object of a derived class. You need
foo::~foo() {};
somewhere as well.

1. 1
2. 2
3. 3
4. 4
frob
15
5. 5

• 10
• 12
• 20
• 12
• 13
• ### Forum Statistics

• Total Topics
632148
• Total Posts
3004450

×