Advertisement Jump to content

Archived

This topic is now archived and is closed to further replies.

soehrimnir

Forcing a method to be implemented by Subclass

This topic is 6348 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

Hello, Suppose I have the following two classes:
  
// A superclass

class SuperClass
{
  public:
    void MethodToBeImplemented(void);
};

// A subclass

class SubClass : public SuperClass
{
  public:
    void MethodToBeImplemented(void);
}

void SubClass::MethodToBeImplemented(void)
{
  cout << "Blablabla";
}
  
Now, how can I force the SubClass to implement the specific method. By forcing I mean a compiler error would be generated if the method wasn''t implemented. Also, the SuperClass should not implement the method. If anyone knows Java, this is what I would like to get as a result, but then in C++:
  
abstract public class SuperClass {
  abstract public void MethodToBeImplemented(void);
}

public class SubClass extends SuperClass {
  public void MethodToBeImplemented(void) {
    System.out.print("Blablabla");
  }
}
  
I know there are abstract classes in C++ too, but I don''t know how they work. The abstract keyword doesn''t exist, so, any ideas?

Share this post


Link to post
Share on other sites
Advertisement
What you want is a pure virtual function, in your example:

    
// A superclass

class SuperClass
{
public:
virtual void MethodToBeImplemented() =0; // this line changed

};

// A subclass

class SubClass : public SuperClass
{
public:
void MethodToBeImplemented();
};

void SubClass::MethodToBeImplemented()
{
cout << "Blablabla";
}


The keyword virtual declares the function to be a virtual function (it can be redefined by child classes). And the =0 means that there is no definition of the funtion within the class hence the class is abstract as it contains at least one 'pure virtual function'.

[edit] Opps, fixed source error due to dodgy c&p. :D [/edit]

Edited by - meh on September 7, 2001 5:52:37 AM

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

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

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!