1

I have looked all over and I can't find any resources on this involving the :: operator.

I have 2 classes: A and B. I also have another class C.

B inherits from A, as does C.

A contains a method called d:

A's .h file:

class A
{
public:
    ...
    void d();
};

A's .cpp file:

...
void A::d()
{
    ...
}

If I have a B or a C, and I run their d, this method should be run if B or C do not have their own overridden d.

I want to override d in B, however it isn't clear to me how I do this. Should I be doing this inside B's .cpp file?:

void A::d()
{
    ...
}

or

void B::d()
{
    ...
}

and declare it in B's .h file?

Or should the function be virtual?

edo
  • 99
  • 1
  • 2
  • 15
  • 5
    It looks like it's time for a good [C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Kerrek SB Apr 08 '17 at 17:06
  • 1
    make the function virtual. If A is abstract then make it private virtual. And then override the function with override keyword in sub class. In C++ the function needs to be virtual there is no automatic invocation like in Java. – Ramandeep Nanda Apr 08 '17 at 17:09
  • @4386427: It's the "scope resolution operator". – Kerrek SB Apr 08 '17 at 17:12

1 Answers1

4

Overriding is a property of virtual member functions, and it is part of a class definition.

Schematically, you want:

struct A
{
    virtual void d() { /* A's implementation */ }
};

struct B : A
{
    void d() override { /* B's override of A::d */ }
};

struct C : A
{
}:

Usage: suppose you have this function:

void g(A & a) { a.d(); }

Then:

B b;
g(b);   // calls b's B::d

C c;
g(c);   // calls c's A::d on the A-subobject of c

(How you split your code into different files has nothing to do with inheritance and overriding.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084