+ 2
Member functions is the name given to any method of a class.
Static methods can be called without instantiating an object, but they can not modify non-static class member variables.
#include <iostream>
class Test
{
public:
static void sayHi()
{
std::cout << "Hi" << std::endl;
}
};
int main()
{
Test::sayHi(); // called without instantiating a Test object
return 0;
}
Virtual methods are useful when using polymorphism. They allow calling a method of a child class using a parent object. They only need to be declared as virtual in parent classes.
#include<iostream>
class Animal
{
public:
virtual void eat()
{
std::cout << "I don't know what I eat." << std::endl;
}
};
class Dog : public Animal
{
public:
void eat()
{
std::cout << "I eat dog food." << std::endl;
}
};
int main()
{
Animal myAnimal = new Dog();
// if the eat method was not virtual the eat method of Animal would be called
// because it is virtual, the eat method of Dog is called
myAnimal->eat();
return 0;
}



