Q_A
Q_A

Reputation: 451

C++ - Conditional virtual functions

My question is, if I have something like

class Base {
 ...
 public:
  virtual void func();
}

void Base::func() {
 //Implementation # 1
}

class Derived1 : public Base {
 ...
 public:
  void func();
}

void Derived1::func() {
 //Implementation # 1
}

class Derived2 : public Base {
 ...
 public:
  void func();
}

void Derived2::func()
 //Implementation # 1
}

class Derived3 : public Base {
 ...
 public:
  void func();
}

void Derived3::func() {
 //Implementation # 2
}

What I'm trying to do is I want Derived1 and Derived2 to use the implementation of func() that was used in Base, but I want Derived3 to use func() a little differently. The problem is, if I make func() virtual in Base, then both Derived1 and Derived2 will need to implement it differently which I don't want. However, if I don't make it virtual, then all derived classes will have the same implantation for func(). How can I get past this problem?

Upvotes: 0

Views: 525

Answers (4)

Cameron
Cameron

Reputation: 98836

A virtual function does not have to be overridden. Derived1 and Derived2 can just not redeclare func().

Only a pure virtual function (declared with = 0) must be overridden by (non-abstract) derived classes.

Upvotes: 6

George Kourtis
George Kourtis

Reputation: 2592

Have you thought to define as virtual func only in derived1 ?

The code that follows works like that ( is that what you intended ? )

#include <stdio.h>
#define X


class Base {

 public:
  void func();
};


void Base::func() {
    printf("Base\n");
}

class Derived1 : public Base {
 public:
  virtual void func();
};

void Derived1::func() { 
    printf("derived1\n"); 
};

class Derived2 : public Base {
 public:
};

class Derived3 : public Base {
 public:
};

int main(int argc, char **argv)
{
    Base b;
    Derived1 d1;
    Derived2 d2;
    Derived3 d3;

    b.func();
    d1.func();
    d2.func();
    d3.func();

    printf("hello world\n");
    return 0;
}

Upvotes: 1

mariosmant
mariosmant

Reputation: 454

Just call inside the func() of Derived1 and Derived2 the Base func() like this

Base::func();

Derived3 func() can have a different implementation.

Upvotes: 0

user1708860
user1708860

Reputation: 1753

Edit

This will work, but unless you need more work done in the function, @Cameron's answer is the correct one.

You can call the base function from the derived function like so:

class Base
{
public:
   virtual void foo() { /* Do something */ };
};

class Derived1 : public Base
{
public:
   virtual void foo() { /* Do something else */ };
};

class Derived2 : public Base
{
public:
   virtual void foo() { Base::foo(); /* Do something */ };
};

Upvotes: 1

Related Questions