04-15-2013, 03:12 PM
|
#54
|
FFR Veteran
Join Date: May 2008
Posts: 1,114
|
Re: Teach me CS stuff for interviews
Okay Reincarnate, I made some code for you :-P
Code:
#include <iostream>
class Animal {
public:
Animal();
~Animal();
/*virtual*/ void make_sound();
};
class Cat : public Animal {
public:
Cat();
~Cat();
void make_sound();
};
Animal::Animal(){}
Animal::~Animal(){}
void Animal::make_sound(){
std::cout << "ROAAAAARRRR" << std::endl;
}
Cat::Cat(){}
Cat::~Cat(){}
void Cat::make_sound(){
std::cout << "Meow" << std::endl;
}
int main(int argc, char* argv[]){
std::cout << "Testing animals" << std::endl;
Animal* animal = new Animal();
Cat* cat = new Cat();
Animal* catanimal = dynamic_cast<Animal*>(new Cat());
std::cout << "animal says "; animal->make_sound();
std::cout << "cat says "; cat->make_sound();
std::cout << "catanimal says "; catanimal->make_sound();
delete animal;
delete cat;
delete catanimal;
return 0;
}
If you declare without the virtual keyword (as is above, where it is commented-out) you get as output
Code:
Testing animals
animal says ROAAAAARRRR
cat says Meow
catanimal says ROAAAAARRRR
But if you do declare the virtual keyword (remove the commenting) you get as output
Code:
Testing animals
animal says ROAAAAARRRR
cat says Meow
catanimal says Meow
Or, basically, yes the virtual keyword does matter a whole lot, and FissionMailed is right.
__________________
Quote:
Originally Posted by Crashfan3
Man, what would we do without bored rednecks?
|
[SIGPIC][/SIGPIC]
|
|
|