I just start to learn it and I tried to find out what are the difference between virtual and not virtual class functions. For this a use a base class with a virtual function which Constructor made the impossible possible - here is example how you can cheat the compiler and make an object with pure virtual function.
#include <iostream>
struct Wolf1 {
virtual void eat()=0;
Wolf1() {
std::cout<<"CONSTR1"<<std::endl;
ptr=this;
ptr->eat(); //Here you program will crash (you can comment this)
}
~Wolf1() {
std::cout<<"DECONSTR1"<<std::endl;
}
} *ptr;
struct Wolf2 : private Wolf1 {
void eat() {
std::cout<<"WOLF2"<<std::endl;
}
Wolf2() {
std::cout<<"CONSTR2"<<std::endl;
ptr->eat();
}
~Wolf2() {
std::cout<<"DECONSTR2"<<std::endl;
}
};
int main() {
Wolf2 my;
system("PAUSE");
return 0;
}
Here you see how you can handle objects with abstract classes. But the general idea I had is that you can now see "the difference between virtual and not virtual class functions". For seeing this just delete the virtual keyword in front of the function and make it a body now the source will look like this:
#include <iostream>
struct Wolf1 {
virtual void eat() { //Here you can remove the "virtual" and see the result
std::cout<<"WOLF1"<<std::endl;
}
Wolf1() {
ptr=this;
}
~Wolf1() {
}
} *ptr;
struct Wolf2 : private Wolf1 {
void eat() {
std::cout<<"WOLF2"<<std::endl;
}
Wolf2() {
ptr->eat();
}
~Wolf2() {
}
};
int main() {
Wolf2 my;
system("PAUSE");
return 0;
}
Output:
if virtual:
WOLF2
else:
WOLF1