Base Keyword on c++?

Hello.

How to use base keyword in c++ inheritance?

In c# if you have a code like this

1
2
3
4
5
6
  public override void Update()
        {
            base.Update();
            Console.WriteLine("called from derived class");
          
        }


you can control which part is going to be executed first.

You can put the base.Update() after the console.writeline. or you can execute the base class update method first before the console.writeline.

how can you do that in c++?
Last edited on
Use the name of the base class explicitly.
1
2
3
4
5
void Update()
{
    BaseClassName::Update();
    std::cout << "called from derived class" << std::endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct A
{
    A( int ) { /* ... */ }
    virtual ~A() = default ;

    virtual void update() { /* ... */ }
};

struct B : A
{
    using base = A ; // 'base' is a type alias for 'A'

    using base::base ; // inheriting constructor
                       // equivalent to B( int v ) : base(v) {}
    B() : base(5) {}

    virtual void update() override
    {
        base::update() ; // same as A::update() ;
        std::cout << "called from derived class\n" ;
    }
};
So that means that I am not really overriding the virtual method of baseclass?

Im just making a new Update() from deriveClass then use the BaseClass::Update()?


public: virtual void update() override in C++ means precisely the same thing as
public override void Update() in C#

The only difference being that if update() is overloaded in the base class, C++ hides by name while C# hides by signature.
I see.. makes sense now..

Also thanks for the code snippet. Makes the explanation clearer.


Thank you very much :D

Last edited on
Topic archived. No new replies allowed.