pure virtual function in c++ syntax code example
Example 1: pure virtual function in c++
#include <iostream>
#include <string>
class Entity {
public:
virtual std::string GetName() = 0;
};
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; };
std::string GetName()override { return m_name; };
};
void PrintName(Entity* entity) {
std::cout << entity->GetName() << std::endl;
}
int main()
{
Player x("Jacob");
std::cin.get();
}
Example 2: abstract class in c++
struct Abstract {
virtual void f() = 0;
};
struct Concrete : Abstract {
void f() override {}
virtual void g();
};
struct Abstract2 : Concrete {
void g() override = 0;
};
int main()
{
Concrete b;
Abstract& a = b;
a.f();
}
Example 3: 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();
}