Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a static method in a derived class call a protected constructor in C++?

Tags:

This code works with clang but g++ says:

error: ‘A::A()’ is protected

class A
{
protected:
    A() {}
};

class B : public A
{
    static A f() { return A(); } // GCC claims this is an error
};

Which compiler is right?

like image 408
John Zwinck Avatar asked Aug 30 '11 19:08

John Zwinck


People also ask

Can static method call constructor?

Static method cannot cannot call non-static methods. Constructors are kind of a method with no return type.

How do you call a protected constructor?

The only way to cause a protected constructor to be called is to derive from the class and have the derived class delegate to it or to have a static method create it or some other internal method.

Can protected constructor can be called directly?

Explanation: Protected access modifier means that constructor can be accessed by child classes of the parent class and classes in the same package.

What happens if a constructor is declared protected?

Protecting a constructor prevents the users from creating the instance of the class, outside the package. During overriding, when a variable or method is protected, it can be overridden to other subclass using either a public or protected modifier only. Outer class and interface cannot be protected.


1 Answers

g++ is right.

The C++ Standard §11.5/1 says that "<...> the access must be through a pointer to, reference to, or object of the derived class itself <...>". In case of constructors, this means that B is allowed to call the protected constructor of A only in order to construct its own base subobject.

Check this related issue in g++. It was closed as not a bug.

like image 59
Kirill V. Lyadvinsky Avatar answered Oct 10 '22 01:10

Kirill V. Lyadvinsky