Home > OS >  C Difference between A foo() and A::foo()
C Difference between A foo() and A::foo()

Time:01-19

When I run the following code:

#include <iostream>
  
class A
{
    public:
    virtual void foo()
    {
        std::cout << "Foo\n";
    }
};

class B : A
{
    public:
    virtual void foo() override
    {
        A foo();
        std::cout << "Bar\n";
    }
};


int main()
{
    B b;
    b.foo();
}

I get the following result: Bar.

I understand that to get:

Foo
Bar

I would need to replace A foo(); with A::foo();. But I'm having trouble understanding what A foo(); is, as it seems that that statement (or declaration?) is skipped.

Note: I'm using g 7.4 on a x86 machine. Thanks!

CodePudding user response:

A foo(); declares a function that has no arguments, returns an A and is called foo.

A::foo(); is something entirely different. It calls the method A::foo.

CodePudding user response:

You are experiencing a phenomenon commonly referred to as most vexing parse. It usually manifests when trying to initialise a variable:

Type variable1;
Type variable2(value);
Type function1();
Type function2(Type);

It is easy to be misled into thinking that Type x(); and Type y(1); should roughly do a similar thing, but the former declares a function while the latter declares and defines a local variable.

In your case in the example, foo is not the member function A::foo but a local declaration of a function that would shadow the member function you are keen on calling.

The fact that this is seldom useful in function scopes is even more vexing, but that's just how the C parser works. Declaration syntax does not distinguish between global and local scope.

  •  Tags:  
  • Related