I just find out that overriding a private function to a public one from base object is allowed in C++ since Visual Studio produces 0 warning. Is there any potential danger to doing that?
If there isn't, what's the difference between declaring a virtual function in private, protected and public in a base object?
what's the difference between declaring a virtual function in
private, protected and public in a base object?
The difference is that a private virtual function can be called only from a base class. This can be useful if the function is not a part of an external class interface, and is only used by base class. So that users call (some other) base class' member, and that member calls the virtual function. For example:
class Base {
virtual void stage1()=0; // derived classes override this
virtual void stage2()=0;
public:
void run() { stage1(); stage2(); } // users call this
};
Moreover, there is a point of view that you should not make your virtual functions public at all, because the fact that they are virtual is internals of the class and its subclasses, and the users should not be aware of that. It is rarely that the same function must be overridden and callable from external code. This allows the base class to control which (virtual) functions can be called from which (non-virtual) public method, making maiteinance easier.
See more details in this article by Herb Sutter:
...each [public] virtual
function is doing two jobs: It's specifying interface because it's
public...; and it's specifying implementation detail,
namely the internally customizable behavior... That a public virtual
function inherently has two significantly different jobs is a sign
that it's not separating concerns well and that we should consider a
different approach. What if we want to separate the specification of
interface from the specification of the implementation's customizable
behavior?
...
In summary, prefer to make base class virtual functions private (or
protected if you really must). This separates the concerns of
interface and implementation, which stabilizes interfaces and makes
implementation decisions easier to change and refactor later.
However, I am not qualified to say whether this is really widely used...
Is there any potential danger to doing that?
I don't think so, because you are still very limited:
class Base
{
private:
virtual void foo(){}
};
class Derived1 : public Base
{
public:
virtual void foo(){ Base::foo(); }
};
class Derived2 : public Base
{
public:
virtual void foo(){}
};
int main()
{
Derived1 d1;
d1.foo(); //error
Base * d2 = new Derived2();
d2->foo(); //error
}
So at best you will be able to call the overloaded function (if it doesn't call the function from the base class from itself), but the function of the base class will still have the same visibility, and will be inaccessible.
When changing access visibility by overriding in derived class, base class visibility doesn't change:
So with:
class Base {
public:
virtual ~Base() = default;
protected:
virtual void foo() = 0;
};
class Derived : public Base {
public:
void foo() override {};
};
Then
Derived d;
Base& b = d;
d.foo(); // valid
b.foo(); // invalid
If there isn't, what's the difference between declaring a virtual function in private, protected and public in a base object?
It depends on how you access the function. The type of the object/pointer you use determines whether you can access the function.
class Base
{
public:
virtual void foo() {}
};
class Derived : public Base
{
private:
virtual void foo() {}
};
int main()
{
Derived* dptr = new Derived;
Base* bptr = dptr;
dptr->foo(); // Can't use it. Derived::foo is private
bptr->foo(); // Can use it. Base::foo is public.
}
Compiler message, using g++ 4.9.3.
socc.cc: In function ‘int main()’:
socc.cc:12:20: error: ‘virtual void Derived::foo()’ is private
virtual void foo() {}
^
socc.cc:20:14: error: within this context
dptr->foo(); // Can't use it. Derived::foo is private
A virtual function is a customization point for derived class implementations. If it is private then it's purely an implementation detail. Making it more accessible in a derived class then exposes an implementation detail, with all that that entails. In particular client code can come to depend on that detail so that the implementation can't be easily changed. It can also be easier for client tode to call in incorrect ways, than the originally intended interface, and it can yield results that are only valid in certain contexts, so that it's more brittle than the original interface.
Related
Is there any point to making virtual member functions, overridden from a base class private, if those are public in the base class?
struct base {
virtual void a();
};
struct derived : base {
// ...
private:
void a() override;
};
If you are forced to do a 2-phase construction on the implementation class (i.e. have an init() method as well as or instead of a constructor that has to be called (I know, but there are reasons), then this stops you calling any /other/ methods directly on the instance pointer before you pass it back as an interface pointer. Go the extra mile, make the inheritance private, and have your one public init function return the interface pointer!
Another reason is you just don't /need/ to write public: in a final implementation class declaration, so then by default everything is private. But why you would do that and use struct instead of class I don't know. Perhaps this was converted from class at some point due to a style war?
Looking at your design, I see one cannot call derived::a directly, but only through a base interface.
Is there any point? Consider that, once we have a derived instance, we can always up-cast to its base, so given
derived d;
while d.a() wouldn't compile, we can always do
base & b = d;
b.a(); //which actually calls derived::a
In other words: derived::a is not that private, after all, and I would discourage this design, which can be confusing to the user.
Things change if the members private in derived are private in base, as well: this time it is clear that they just cannot be called directly, outside base or derived.
Let's say we have a couple of functions, and want them to be called conditionally, according to a value passed as an argument to a third one:
struct base
{
void dosomething(bool x)
{
if(x)
{
do_this();
}
else
{
do_that();
}
}
private:
virtual void do_this(){}
virtual void do_that(){}
};
Thus a derived class could be like:
struct derived : base
{
private:
void do_this() override { }
void do_that() override { }
};
and no other class can call them, unless it extended base itself:
derived d;
d.dosomething(true); //will call do_this() in derived
d.dosomething(false); //will call do_that() in derived
d.do_that() //won't compile
Yes, if you inherit the base class as private. Otherwise, it is more of a weird explicit-like restriction - user has to has to make an explicit conversion to use the function - it is generally ill advised as few will be able to comprehend the author's intention.
If you want to restrict some functions from base class, make a private/protected inheritance and via using keyword declare which base-methods you want to be protected/public in the derived class.
The same reasoning as for non-virtual methods applies: If only the class itself is supposed to call it make it private.
Consider the template method pattern:
struct base {
void foo() { a() ; b(); }
virtual void a() = 0;
virtual void b() = 0;
};
struct derived : base {
private:
void a() override {}
void b() override {}
};
int main()
{
derived().foo();
}
Perhaps a and b should have been protected, but anyhow the derived can change accesibility and it requires some documentation so that derived knows how it is supposed to implement a and b.
I have a question about using the keyword final in C++. I understand that virtual function is a member function that is declared in the base class, and it is expected to be overridden in the derived classes. By dynamic binding, an appropriate method will be called, depending on the type of the object responsible for the call. However, to prevent a member function in a base class from being overridden in any derived class, we will use the final keyword.
void startEngine() final;// Compile error!
virtual void startEngine() final; //No error
Why we use "final" to PREVENT a member function in the base class from being overridden in derived class meanwhile we still have to use the keyword VIRTUAL (ALLOW to override) together.
I tried to delete the word virtual, but I got a compile error: "nonvirtual function cannot be declared with 'final' modifier"
First at all, we only can stop overriding functions if they can be overridden at all. So final only makes sense on virtual functions at all.
Still, final applied on a single class's virtual function might appear pretty meaningless. But if you consider a more complex hierarchy, matter changes:
class Parent
{
public:
virtual ~Parent() = default;
virtual void f();
};
class Child : public Parent
{
public:
void f() final; // f IS virtual already...
};
class GrandChild : public Child
{
// cannot override f any more – while Child still could!
};
Additionally, consider the following:
class Base
{
public:
virtual ~Base() = default;
void f(); // non-virtual! (i. e. cannot be overridden)
};
class Derived : public Base
{
public:
void f(); // does not override, but HIDEs Base::f!!!
};
Declaring Base::f both virtual and final would prevent hiding as well (but not overloading).
Actually, again this scenario rather makes sense if Base itself already inherited from another polymorphic class. If not and Base is not intended to be inherited, I'd not introduce any virtual functions at all (virtual function calls are more costly than normal function calls!). If then a user still inherits and hides a function – well, his own responsibility...
I have an abstract class AUnit with variables and getters/setters in virtual pure like this
class AUnit {int var... int getVar() const = 0 ... }
All the data is in protected: except constructor and destructor.
I have Berserk and Tank as child like this
class Berserk : public AUnit
{
...
private:
int getVar() const;
In their .cpp, I write the code of the getters and setters. Nothing special.
But I have one other class (foo for example) like this
class Foo : public Berserk, public Tank
who need to access the data in Berserk or Tank so I changed the private keyword by protected, here is the error :
Tank.hpp:36:25: erreur: ‘virtual int Tank::getY() const’ is protected
error inside the context
As first, I just tried to access the data with the AUnit getter but cause of virtual pure and abstract concepts, I thought to reinterpret_cast my AUnit in his real type after passing getType of AUnit in non-pure and in public. Still not working, its the scheme I told you earlier.
It's just classical heritage, can I have some help ?
Your code snipped is certainly incomplete. My guess is that you have something like this:
int Foo::f(Tank const* tank) {
return tank->getY();
}
(probably, you are doing something more interesting with value than returning it).
Even though access to Tank::getY() is protected, the class Foo won't have access to getY() in the above code because the object pointed to by tank is not known to be a Foo object: a class has only access to protected members in a base object of its own type! That is, the following would be OK:
int Foo::f(Foo const* foo) {
return foo->getY();
}
So far the only good use I have found for protected a virtual member functions which have a reasonable an non-trivial implementation in a base class and which are called from a [further] derived class as part of overriding the member. This way, functionality can be added and the common logic can be used (of course, any virtual function is not public but rather private or protected).
It is generally a bad idea to give the overriding function a stricter access protection than the function it overrides. Consider:
class Base {
public:
virtual void f() {}
};
class Derived : public Base {
private:
virtual void f() {} // overrides Base::f
};
Derived d;
d.f(); // error - f is private
Base* pb = &d;
pb->f(); // OK - calls d.f()
To avoid such paradoxes, it is prudent to put overrides at the same access level as the original (or the more relaxed access level, though that's somewhat unusual).
Consider the following base class:
class Base
{
public:
virtual ~Base(void);
virtual void foo(void);
virtual void bar(void) = 0;
}
Now suppose I know that a given class should be the most derived class of Base. Should I declare the functions virtual? The most derived class can/will be used polymorphically with Base.
For example, should I use MostDerived1 or MostDerived2?
class MostDerived1 : public Base
{
public:
~MostDerived1(void);
void foo(void);
void bar(void);
}
class MostDerived2 : public Base
{
public:
virtual ~MostDerived2(void);
virtual void foo(void);
virtual void bar(void);
}
I'm leaning towards MostDerived1 because it most closely models the intent of the programmer: I don't want another child class of MostDerived1 to be used polymorphically with MostDerived1.
Is this reasoning correct? Are there any good reasons why I should pick MostDerived2, aside from the obvious there could be a >0% chance MostDerived2 should be used polymorphically with any deriving classes (class OriginalAssumptionWrong : public MostDerived2)?
Keep in mind MostDerived1/MostDerived2 can both be used polymorphically with Base.
Adding virtual to derived classes doesn't change their behavior, MostDerived and MostDerived2 are have exactly the same behavior.
It does however document your intention, however. I would recommend it for that purpose. The override keyword also helps with this, assuming its available on your platform.
You can't turn off virtualness. Another class derived from either MostDerived1 or MostDerived2 can also override any of the virtual functions regardless of whether you omit the virtual keyword somewhere in the class hierarchy or not.
If you want to enforce that no other class derives from MostDerived1, define it as
class MostDerived1 final : public Base
{
// ...
};
The final keyword can also be used for individual virtual member functions, ensuring no derived class overrides that specific function.
Once function declear somewhere at the hierarchy as a virtual, it's virtual for ever.
You can use final or override if you using C++11
Here is a sample of code that annoys me:
class Base {
protected:
virtual void foo() = 0;
};
class Derived : public Base {
private:
Base *b; /* Initialized by constructor, not shown here
Intended to store a pointer on an instance of any derived class of Base */
protected:
virtual void foo() { /* Some implementation */ };
virtual void foo2() {
this->b->foo(); /* Compilator sets an error: 'virtual void Base::foo() is protected' */
}
};
How do you access to the protected overrided function?
Thanks for your help. :o)
Protected members in a base-class are only accessible by the current object.
Thus, you are allowed to call this->foo(), but you are not allowed to call this->b->foo(). This is independent of whether Derived provides an implementation for foo or not.
The reason behind this restriction is that it would otherwise be very easy to circumvent protected access. You just create a class like Derived, and suddenly you also have access to parts of other classes (like OtherDerived) that were supposed to be inaccessible to outsiders.
Normally, you would do it using Base::foo(), which refers to the base class of the current instance.
However, if your code needs to do it the way you're trying to and it's not allowed, then you'll need to either make foo() public or make Derived a friend of Base.
One solution would be to declare a static protected function in Base that redirects the call to the private / protected function (foo in the example).
Lets say:
class Base {
protected:
static void call_foo(Base* base) { base->foo(); }
private:
virtual void foo() = 0;
};
class Derived : public Base {
private:
Base* b;
protected:
virtual void foo(){/* Some implementation */};
virtual void foo2()
{
// b->foo(); // doesn't work
call_foo(b); // works
}
};
This way, we don't break encapsulation because the designer of Base can make an explicit choice to allow all derived classes to call foo on each other, while avoiding to put foo into the public interface or explicitly turning all possible subclasses of Base into friends.
Also, this method works regardless of whether foo is virtual or not, or whether it is private or protected.
Here is a link to a running version of the code above and here another version of the same idea with a little more business logic.
It's a bit fragile, but with the classes you defined here, won't this work?
virtual void foo2() {
reinterpret_cast<Derived *>(this->b)->foo();
}
The reinterpret_cast points at the VTABLE for the base object, and calls it through this members accessor.
You call base functions explicitly with the scope operator (Base::foo()). But in this case, the Base class doesn't define foo (it's pure virtual), so there's actually no function to execute when you say this->b->foo(); since b is a pointer to Base and not Derived.
How do you access to the protected
overrided function?
--- from where?
You can access a protected member only via inheritance (apart from the methods of the same class). Say for example you have a class Derived1 which inherits from Derived, then objects of Derived1 can call foo().
EDIT: MSDN article on protected access specifier.