can we have 2 virtual functions in a class code example

Example 1: virtual function in c++

#include <iostream>
#include<string>
	//Virtual Functions are functions that allow us to override methods in subclasses
//In this example  we have an entity class as a base class and class player inherits from public entity 
class Entity {
public:
	virtual std::string GetName() { return "Entity"; }//It is a method in base class that we want to modify in sub class Player
	void Print() { std::cout << "This is Base class" << std::endl;}//function that is not virtual
};
class Player :public Entity {
	std::string m_name;

public:
	Player(const std::string& name)
		:m_name(name)
	{};
	void Print() { std::cout << "This is Sub class" << std::endl; };//function that is not virtual
	std::string GetName()override { return m_name; };//overriding the function in sub class
};

int main()
{
	Entity* e = new Entity();
	std::cout << e->GetName() << std::endl;
	Player* p = new Player("Jacob");
	std::cout << p->GetName() << std::endl;
	PrintName(p);// This function calls the GetName method from the Player instance despite it takes an entity instance as a parameter this is because player class is a sub  class of Entity and the method is marked virtual it will map with the method in the Player class and call it from there .It outputs => Jacob
	//if It was not virtual it would have called The method From Entity Instance and output would be => Entity
	Entity* notvirtualentity = new Entity();
	Player* notvirtualpalyer = new Player("XX");
	notvirtualentity =  notvirtualpalyer;
	notvirtualentity->Print();//It prints => this is base class if it was virtual function it would call print function from Player Class and print => This is subclass
	std::cin.get();
}

Example 2: virtual function c++

#include <iostream>
#include <string>

class Entity {
public:
  virtual std::string getName();
  void print(); 
};

virtual std::string Entity::getName() {
	return "Entity";
}

void Entity::print() {
	std::cout << "This is the base class" << std::endl;
}

class Player : public Entity {
  std::string m_name;
public:
	Player(const std::string& name): m_name(name) {};
  	void print();
  	virtual std::string getName();
};

virtual std::string Player::getName() {
	return m_name;
}

void Player::print() {
	std::cout << "This is the sub class" << std::endl;
}

int main() {
	Entity* e = new Entity();
  	std::cout << e->getName() << std::endl;
  	Player* p = new Player("Jacob");
  	std::cout << p->getName() << std::endl;
  	p->print();
  	e->print();
  
  	Entity* notVirtualEntity = new Entity();
  	Player* notVirtualPlayer = new Player("Bob");
  	notVirtualEntity = notVirtualPlayer;
  	notVirtualEntity->print();
  	notVirtualEntity->getName();
}

Tags:

Cpp Example