I use a pure virtual method as shown in the code below.
#include <iostream>
using namespace std;
class Advertisment
{
public:
vitual void price (int Uchrg, int no_of_unt) = 0;
{
}
};
class TVadvertisment : public Advertisment
{
public:
void price (int Uchrg, int no_of_unt)
{
int adPrice = Uchrg * no_of_unt;
cout << "Advertisment Price: " << adPrice;
}
};
int main()
{
TVadvertisment T;
T.price(1000, 60);
return 0;
}
As I know a pure virtual function will be declared as virtual void display() = 0;
. But the Code::Blocks compiler show an error because of this = 0
. Without that it will compile successfully.
And also I didn't use pointers to call methods of derived class.
Your function is pure virtual, which means the method is virtual and not even implemented in the base class (= 0)
.
So you have to delete the block after it.
It has to be:
virtual price(int Uchrg, int no_of_unt) = 0;
without the { }
.
Virtual means, that classes that inherit from a base class can override the method and called via the base class interface. If a class has a pure virtual method, the class is abstract and this function needs to be overridden by classes that inherit from that base class to be instantiated.
In short:
Virtual:
virtual price(int Uchrg, int no_of_unt)
{
// Implementation
}
Has an implementation is the base class. Sub classes does not need to override, but they can. The class is not abstract and can be instanciated.
Pure virtual:
virtual price(int Uchrg, int no_of_unt) = 0; // No implementation
There is no implementation, the sub classes must override this to be not abstract.
Call a virtual method via base class:
Base* pBase = new Derived;
pBase->fun();
The method is called via the interface of the base class, but it will be the derived class' method.