Sign in to follow this  

multiple base classes with virtual functions.

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

OK, apparently you cannot create a derived class from a base class if both classes have polymorphic functions. for example:

 

Base Class:

class A
{
public:
    A(){}
    
    ~A(){}
    
    virtual void init() = 0;
   
    virtual void deleted() = 0;
};

void A::init()
{
}

void A::deleted()
{
}
 

 

 Derived class one:

class B : public A
{
public: 
    B(){}

    ~B(){}
   
    virtual void init() = 0;

    virtual void deleted() = 0;
}

void B::init()
{}

void B::deleted()
{}

Derived Class # 2

 

class C : public B
{
public:
    C(){}

    ~C(){}

    void init();

    void deleted();
};

void C::init()
{}

void C::deleted()
{}

program:

 

int main()
{
   C* c = new B();
}

this will produce errors saying how you can't instaciate B because of the virtual functions in both A and B but this needs to work because I would make render specific resource and has to be able to use something like:

 

class IResource
{
  public:
     // virtual functions common to all resources.
}

class IHardwareMaterial : public IResource
{
public:
    // virtual functions related to a hardware material.
}

class ID3D9HardwareMaterial : IHardwareMaterial
{}

I'm not sure if I explained my self well. This is all pseudo code, sort of so I'm not sure if I'm communicating this right.

Share this post


Link to post
Share on other sites

[source]
class B : public A
{
public:
  B(){}
  ~B(){}
  virtual void init();  //< do not declare these are pure virtual! This only needs to happen in A.
  virtual void deleted();
}

void B::init() //< because you're declaring the implementations here!
{}
void B::deleted()
{}
[/source]

Edited by RobTheBloke

Share this post


Link to post
Share on other sites

p.s. This will not work!

[source]
int main()
{
   C* c = new B();
}
[/source]

However this will .....

[source]
int main()
{
   A* a = new B();
}
[/source]

Edited by RobTheBloke

Share this post


Link to post
Share on other sites

You can either implement you methods or declare them pure virtual, but not both.

 

Actually that's not true.  A pure virtual function can have an implementation, you just can't instantiate a class with a pure virtual function.  You can still call the pure virtual function from a derived class.

 

They covered it in more detail here: http://stackoverflow.com/questions/2089083/pure-virtual-function-with-implementation

Share this post


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