Jump to content
  • Advertisement
Sign in to follow this  
namnam

C++ base class calling method in derived class

This topic is 4497 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
Guest Anonymous Poster
Thank you all.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!