Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between virtual void funcFoo() const = 0 and virtual void funcFoo() = 0;

I have a declaration in a cpp where a function is like:

virtual void funcFoo() const = 0; 

I assume that can be inherited by another class if is declared explicit, but what's the difference between

virtual void funcFoo() = 0; 

Is important to me improve my programming and i want to know the difference. I don't want a malfunction caused by a bad inherit.

Thanks in advance.

like image 779
vgonisanz Avatar asked Apr 02 '12 09:04

vgonisanz


People also ask

What is difference between virtual function and pure virtual function?

A virtual function is a member function in a base class that can be redefined in a derived class. A pure virtual function is a member function in a base class whose declaration is provided in a base class and implemented in a derived class.

What does Const 0 do in C++?

class Shape { public: virtual void draw() const = 0; // = 0 means it is "pure virtual" ... }; This pure virtual function makes Shape an ABC. If you want, you can think of the "= 0;" syntax as if the code were at the NULL pointer.

Can a virtual function be const?

No, because virtual void func() is not an override for virtual void func() const .

Why do we use virtual void in C++?

A C++ virtual function is a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword. It is used to tell the compiler to perform dynamic linkage or late binding on the function.


2 Answers

The first signature means the method can be called on a const instance of a derived type. The second version cannot be called on const instances. They are different signatures, so by implementing the second, you are not implementing or overriding the first version.

struct Base {    virtual void foo() const = 0; };  struct Derived : Base {    void foo() { ... } // does NOT implement the base class' foo() method. }; 
like image 160
juanchopanza Avatar answered Oct 22 '22 05:10

juanchopanza


virtual void funcFoo() const = 0; // You can't change the state of the object. // You can call this function via const objects. // You can only call another const member functions on this object.  virtual void funcFoo() = 0; // You can change the state of the object. // You can't call this function via const objects. 

The best tutorial or FAQ I've seen about const correctness was the C++ FAQ by parashift:
http://www.parashift.com/c++-faq-lite/const-correctness.html

like image 39
felipe Avatar answered Oct 22 '22 06:10

felipe