Pure Virtual Function

Hi there

I am reading book and there is something I am not 100% sure and need a clarification.

this is extract from book:
"...Once you have placed a pure virtual function in the base class, you must override it in all the derived classes from which you want to instantiate objects. If class doesn't override the pure virtual function, it becomes an abstract class itself, and you can't instantiate objects from it. For consistency you may want to make all the virtual functions in the base class pure."

My question is if derived class Derived1 have function show() then it does override and it will not become abstract class.
What if (does this make sense?) Dervied1 have no such function like show()
but show1()??


thanks :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>


class Base                                                          // base class
{
public:
	virtual void show() = 0;                                            // this is PURE virtual function
};

class Derived1 : public Base                                        // derived class 1
{
public:
	void show()
	{
		std::cout << "Derived1 " << std::endl;                      //this will be executed this time
	}
};

class Derived2 : public Base
{
public:
	void show()
	{
		std::cout << "Derived2 " << std::endl;                      //this will be executed this time
	}
};

int main() {
	
	//Base bad; // this is not going to work due to fact that BAD object is from PURE virtual class
	Base* array[2];                                                  // array of pointers to base class
	Derived1 derived1;
	Derived2 derived2;
	
	array[0] = &derived1;
	array[1] = &derived2;
	
	array[0]->show();                                               // execute show in both objects
	array[1]->show();
	system("pause");
	return 0;
}
Last edited on
Q:
What if (does this make sense?) Dervied1 have no such function like show()

A:
If class doesn't override the pure virtual function, it becomes an abstract class itself, and you can't instantiate objects from it.


Q:
Dervied1 have no such function like show() but show1()?

A: Like in this:
1
2
3
4
5
6
7
8
class Base
{
};

class Derived : public Base
{
  void foo();
}

It is legal for a derived class to have functions that the base does not have. That is totally unrelated to overriding members.
> What if (does this make sense?) Dervied1 have no such function like show() but show1()??
call it `slartibartfast()' if you want, it's another function.
Hi keskiverto and ne555

thank you for clarification :)
Topic archived. No new replies allowed.