Thread: Abstract function with different parameters?

  1. #1
    Registered User
    Join Date
    Sep 2005

    Abstract function with different parameters?

    I am making a small game to test my skills.

    I have an Entity class, which is the base class for pretty much anything. It has a Create function which renders my 2d sprite at a given x, y. That is what is similar to each entity, but each entity is different and I need to pass data to it that defines what kind of the specific entity it is.

    Sounds confusing, so I'll try to show you what I mean:

    struct EnemyDefinition
    	int image_number;
    	int health;
    	float speed;
    	char sprite_file[255]; //filename to use to make sprite
    My create function would be:
    Enemy::Create (int x, int y, EnemyDefinition *def)
    Now that is just one Entity (Enemy is derived from Entity). Let's say I have a Player entity. The Create function would be the same, except it would be Enemy::Create (int x, int y, PlayerDefinition *def). The third parameter is different in each Entity so I don't think I can use a pure virtual function, yet what I am trying to do it seems like I should be using one - since every single Entity has a Create function. Is there a smarter way to do this?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    You can create a Definition abstract base class, then define a hierarchy of Definition objects. Enemy::Create() would then take a pointer to a Definition, upon which you can pass a pointer to a PlayerDefinition and let polymorphism do the job.

    Before you do this though, why not show what is your current class hierarchy, and what each class is for?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  3. const at the end of a sub routine?
    By Kleid-0 in forum C++ Programming
    Replies: 14
    Last Post: 10-23-2005, 06:44 PM
  4. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  5. Replies: 5
    Last Post: 02-08-2003, 07:42 PM