Reputation: 12963
I would like a class B not to be able to redefine one of the member function of its base class A. Is there a way to do that?
EDIT:
Thanks for the answers. Can I prevent non-virtual member functions from being overridden as well?
Upvotes: 3
Views: 1384
Reputation: 6137
Can I prevent non-virtual member functions from being overridden as well?
No you can't, BUT from another side you can... if you're not shore if will you acctualy override base method or not in your derived class you can check whther you're overriding an method or not using a keywod override
when applying that keywod to your method you make shore that you accutaly realy want override that mathod.
so if signature of inherted method is the same as the signature of base method you'll get compile time error, say that derived method does not override base method.
so using override
keyword you are telling the compiler that you DO NOT want to everride it.
by not using override keywod you never know wether you override it or not.
consider following example:
class A
{
public:
void f() {std::cout << "A";}
};
class B : public A
{
public:
void f() override {std::cout << "B";}
};
this result in compile time error because you can't override base method. by not using the override keyword you'll of course be able to override it.
override keywod is introduced in C++0x standard and is supported by visual studio 2010.
Upvotes: 0
Reputation: 131789
If you mean disallowing a derived class to override a virtual function of its base class, C++11 introduced a way to do that with a final
virt-specifier (as it's called in the standard):
struct B{
virtual void f() final;
};
struct D : B{
void f(); // error: 'B::f' marked 'final'
};
I don't know which compilers support that, though. Probably GCC 4.7 and Clang.
Upvotes: 3
Reputation: 258568
If your methods are virtual
, in C++11 you can prevent overriding them with final
.
class A
{
public:
virtual void foo() final;
};
class B : public A
{
public:
void foo(); // <-- error
};
You can't prevent hiding.
Upvotes: 2