Sign in to follow this  
namnam

C++ base class calling method in derived class

Recommended Posts

namnam    122
Hi all I'm having trouble compiling this code:
#include <iostream>

class Animal {
public:
	Animal() {
		makeSound();
	};
	virtual void makeSound() = 0;
};

class Lion : public Animal {
public:
	virtual void makeSound() {
		std::cout << "roar!";
	};
};

int main() {
	new Lion();
	return 0;
}
Compiler says:
Quote:
error: abstract 'virtual void Animal::makeSound()' called from constructor
I guess the problem lies in how objects are created -- from the bottom and up (?). So when the Animal constructor gets called, makeSound in Lion isn't defined yet. This is a pattern I'm used to from Java, and as I'm a bit new to C++ I'd be glad if someone could tell me about the best alternative. Is there a way for a base class to call a method defined in a subclass? Thanks in advance!

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
Sometimes a separate initialize method is necessary...


#include <iostream>

class Animal {
public:
Animal() {
}

virtual void initialize() {
std::cout << "Initialize Lion\n";
makeSound();
}

virtual void makeSound() = 0;
};

class Lion : public Animal {
public:
Lion() {
}

virtual void initialize() {
Lion::initialize(); // initialize parent
std::cout << "Initialize Lion\n";
makeSound();
}

virtual void makeSound() {
std::cout << "roar!\n";
};
};

int main() {
new Lion();
return 0;
}



--StevenAshley

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
Just make sure you initialize it ;)


int main() {
Lion * lion = new Lion();
lion->initialize();
delete lion;
return 0;
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this