Is Virtual destructor rule inherited or not? [duplicate] - c++11

With the struct definition given below...
struct A {
virtual void hello() = 0;
};
Approach #1:
struct B : public A {
virtual void hello() { ... }
};
Approach #2:
struct B : public A {
void hello() { ... }
};
Is there any difference between these two ways to override the hello function?

They are exactly the same. There is no difference between them other than that the first approach requires more typing and is potentially clearer.

The 'virtualness' of a function is propagated implicitly, however at least one compiler I use will generate a warning if the virtual keyword is not used explicitly, so you may want to use it if only to keep the compiler quiet.
From a purely stylistic point-of-view, including the virtual keyword clearly 'advertises' the fact to the user that the function is virtual. This will be important to anyone further sub-classing B without having to check A's definition. For deep class hierarchies, this becomes especially important.

The virtual keyword is not necessary in the derived class. Here's the supporting documentation, from the C++ Draft Standard (N3337) (emphasis mine):
10.3 Virtual functions
2 If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and ref-qualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.

No, the virtual keyword on derived classes' virtual function overrides is not required. But it is worth mentioning a related pitfall: a failure to override a virtual function.
The failure to override occurs if you intend to override a virtual function in a derived class, but make an error in the signature so that it declares a new and different virtual function. This function may be an overload of the base class function, or it might differ in name. Whether or not you use the virtual keyword in the derived class function declaration, the compiler would not be able to tell that you intended to override a function from a base class.
This pitfall is, however, thankfully addressed by the C++11 explicit override language feature, which allows the source code to clearly specify that a member function is intended to override a base class function:
struct Base {
virtual void some_func(float);
};
struct Derived : Base {
virtual void some_func(int) override; // ill-formed - doesn't override a base class method
};
The compiler will issue a compile-time error and the programming error will be immediately obvious (perhaps the function in Derived should have taken a float as the argument).
Refer to WP:C++11.

Adding the "virtual" keyword is good practice as it improves readability , but it is not necessary. Functions declared virtual in the base class, and having the same signature in the derived classes are considered "virtual" by default.

There is no difference for the compiler, when you write the virtual in the derived class or omit it.
But you need to look at the base class to get this information. Therfore I would recommend to add the virtual keyword also in the derived class, if you want to show to the human that this function is virtual.

The virtual keyword should be added to functions of a base class to make them overridable. In your example, struct A is the base class. virtual means nothing for using those functions in a derived class. However, it you want your derived class to also be a base class itself, and you want that function to be overridable, then you would have to put the virtual there.
struct B : public A {
virtual void hello() { ... }
};
struct C : public B {
void hello() { ... }
};
Here C inherits from B, so B is not the base class (it is also a derived class), and C is the derived class.
The inheritance diagram looks like this:
A
^
|
B
^
|
C
So you should put the virtual in front of functions inside of potential base classes which may have children. virtual allows your children to override your functions. There is nothing wrong with putting the virtual in front of functions inside of the derived classes, but it is not required. It is recommended though, because if someone would want to inherit from your derived class, they would not be pleased that the method overriding doesn't work as expected.
So put virtual in front of functions in all classes involved in inheritance, unless you know for sure that the class will not have any children who would need to override the functions of the base class. It is good practice.

There's a considerable difference when you have templates and start taking base class(es) as template parameter(s):
struct None {};
template<typename... Interfaces>
struct B : public Interfaces
{
void hello() { ... }
};
struct A {
virtual void hello() = 0;
};
template<typename... Interfaces>
void t_hello(const B<Interfaces...>& b) // different code generated for each set of interfaces (a vtable-based clever compiler might reduce this to 2); both t_hello and b.hello() might be inlined properly
{
b.hello(); // indirect, non-virtual call
}
void hello(const A& a)
{
a.hello(); // Indirect virtual call, inlining is impossible in general
}
int main()
{
B<None> b; // Ok, no vtable generated, empty base class optimization works, sizeof(b) == 1 usually
B<None>* pb = &b;
B<None>& rb = b;
b.hello(); // direct call
pb->hello(); // pb-relative non-virtual call (1 redirection)
rb->hello(); // non-virtual call (1 redirection unless optimized out)
t_hello(b); // works as expected, one redirection
// hello(b); // compile-time error
B<A> ba; // Ok, vtable generated, sizeof(b) >= sizeof(void*)
B<None>* pba = &ba;
B<None>& rba = ba;
ba.hello(); // still can be a direct call, exact type of ba is deducible
pba->hello(); // pba-relative virtual call (usually 3 redirections)
rba->hello(); // rba-relative virtual call (usually 3 redirections unless optimized out to 2)
//t_hello(b); // compile-time error (unless you add support for const A& in t_hello as well)
hello(ba);
}
The fun part of it is that you can now define interface and non-interface functions later to defining classes. That is useful for interworking interfaces between libraries (don't rely on this as a standard design process of a single library). It costs you nothing to allow this for all of your classes - you might even typedef B to something if you'd like.
Note that, if you do this, you might want to declare copy / move constructors as templates, too: allowing to construct from different interfaces allows you to 'cast' between different B<> types.
It's questionable whether you should add support for const A& in t_hello(). The usual reason for this rewrite is to move away from inheritance-based specialization to template-based one, mostly for performance reasons. If you continue to support the old interface, you can hardly detect (or deter from) old usage.

I will certainly include the Virtual keyword for the child class, because
i. Readability.
ii. This child class my be derived further down, you don't want the constructor of the further derived class to call this virtual function.

Related

Misleading description concerning the 'final' Keyword in the C++11 standard?

class A
{
virtual void foo();
}
class B : public A
{
void foo() final;
}
Quote from C++11 standard § 9.2/8:
A virt-specifier-seq shall contain at most one of each virt-specifier. A virt-specifier-seq shall appear only in the declaration of a virtual member function (10.3)
A virt-specifier includes final and override.
Function foo in class B is a derived virtual member function (even not declared as virtual in B). This is legal according to the above quote from the C++11 standard.
But what is with the following case:
class C
{
virtual void bar() final;
}
According to the C++11 standard class C should compile, though the virtual and final keywords are contrary.
Therefore the C++11 standard $9.2/8 confused me a little bit. It's not precise enough. I don't even know if this really compiles, and if its behaviour is well defined.
"though the virtual and final keywords are contrary". No. The statement you have quoted says only that you cannot use multiple override or multiple final keywords in the same declaration. virtual itself is optional and redundant if any of them are given. The virtual keyword in C as well as in B is optional, because the base class already declares that method virtual. A final method is always virtual, too. It is not useful (and probably illegal - but not sure about the standard) to use final on something that is not an overridden method from the base class.
In previous versions of the C++ standard, final and override did not exist, so it was customary to declare overrides virtual for readability. Now you have override, which not only makes it obvious that this is an override, but also generates a compiler error if it is not (e.g. because the method name in the overriding class has a typo). For backward compatibility, declaring virtual and override was kept legal.
virtual void bar() final;
^^^^^
That is the virt-specifier-seq. It contains final, which is a virt-specifier, and there is one of them.
This is perfectly legal. As is this:
virtual void bar() final override;
^^^^^^^^^^^^^^
It is in the declaration of a virtual member function, and contains at most one of each virt-specifier.
What is illegal is
virtual void bar() final final;
^^^^^^^^^^^
here, it contains two final, which violates the rule "at most one of each virt-specifier".

C++ efficient implementation of wrapper classes

I have a project that makes extensive use (high frequency) of a limited set of key linear algebra operations such as matrix multiplication, matrix inverse, addition, etc. These operations are implemented by a handful of linear algebra libraries that I would like to benchmark without having to recompile the business logic code to accommodate the different mannerisms of these various libraries.
I'm interested in figuring out what is the smartest way of accommodating a wrapper class as an abstraction across all of these libraries in order to standardize these operations against the rest of my code. My current approach relies on the Curiously Recurring Template Pattern and the fact that C++11 gcc is smart enough to inline virtual functions under the right circumstances.
This is the wrapper interface that will be available to the business logic:
template <class T>
class ITensor {
virtual void initZeros(uint32_t dim1, uint32_t dim2) = 0;
virtual void initOnes(uint32_t dim1, uint32_t dim2) = 0;
virtual void initRand(uint32_t dim1, uint32_t dim2) = 0;
virtual T mult(T& t) = 0;
virtual T add(T& t) = 0;
};
And here is an implementation of that interface using e.g. Armadillo
template <typename precision>
class Tensor : public ITensor<Tensor<precision> >
{
public:
Tensor(){}
Tensor(arma::Mat<precision> mat) : M(mat) { }
~Tensor(){}
inline void initOnes(uint32_t dim1, uint32_t dim2) override final
{ M = arma::ones<arma::Mat<precision> >(dim1,dim2); }
inline void initZeros(uint32_t dim1, uint32_t dim2) override final
{ M = arma::zeros<arma::Mat<precision> >(dim1,dim2);}
inline void initRand(uint32_t dim1, uint32_t dim2) override final
{ M = arma::randu<arma::Mat<precision> >(dim1,dim2);}
inline Tensor<precision> mult(Tensor<precision>& t1) override final
{
Tensor<precision> t(M * t1.M);
return t;
}
inline Tensor<precision> add(Tensor<precision>& t1) override final
{
Tensor<precision> t( M + t1.M);
return t;
}
arma::Mat<precision> M;
};
Questions:
Does it make sense to use CRTP and inlining in this scenario?
Can this be improved with respect to optimizing performance?
As pointed out in an answer, the use of polymorphism here is a bit odd due to the templating of the base class. Here is why I think this still makes sense:
You will notice the base class is named "Tensor" rather than something more specific like "ArmadilloTensor" (after all, the base class implements ITensor methods using Armadillo methods). I kept the name as is because according to my current design, the use of polymorphism is more due to a sense of formalism than anything else. The plan is for the project code to be aware of a class called Tensor that offers the functionality specified in ITensor. For each new library that I want to benchmark, I would just write a new "Tensor" class in a new compilation unit, package the compilation results into an .a archive, and when doing a benchmarking test, link the business logic code against that library. Switching between different implementations then becomes a matter of choosing which Tensor implementation to link against. To the base code it is all the same whether the Tensor methods are implemented by Armadillo or something else. Advantages: avoids having code that knows about every library (they are all independent), and no compile time changes are required in the base code in order to use a new implementation. So, why the polymorphism? In my mind I just wanted to somehow formalize the functions that need to be implemented by any new library that is added to the benchmark. In reality, the base code would then work with ITensors in the function parameters, but then potentially static_cast them down to Tensors in the method bodies themselves.
It's possible I'm missing something here, or you haven't shown enough details.
You use polymorphism. As defined in its name, it's about same type taking different shapes (different behaviour). So you have an interface that is accepted by user code and you can provide different implementations of that interface.
But in your case you don't have different implementations of a single interface. Your ITensor template generates different classes and each final implementation of your Tensor derives from a distinct base.
Consider your user code is something like this:
template<typename T>
void useTensor(ITensor<T>& tensor);
and you can provide your Tensor implementation. It's almost the same as
template<typename T>
void useTensor(T& tensor);
just w/o CRTP and virtual calls. Now each wrapper should implement some set of functionality. There's a problem that this set of functionality is not explicitly defined. Compiler provides a great help here but it's not ideal. It's why we all look forward to get Concepts in the next standard.

Enums support for inheritance

I frequently come across a situation where we create a class that acts on some enumeration, but later we derive and we want to add more values to the enumeration without changing the base class.
I see this question from 2009:
Base enum class inheritance
However, I know there were a number of changes to enum in C++11, 14, 17.
Do any of those changes allow for extension of enums from base class to derived?
class Base
{
enum State {STATE_1, STATE_2, STATE_3};
};
class Derived : public Base
{
enum State {STATE_4};
};
...where we want derived to have an enumeration describing the states it can be in, which are: STATE_1, STATE_2, STATE_3, and STATE_4. We don't really want to change the enumeration in the base class, because other derived classes might not have the ability to be in STATE_4. We don't really want to create a new enumeration either, because we already have one for State in the Base.
Do we still use static const values instead in order to accomplish this 8 years later?
class Base
{
static int STATE_1= 0;
static int STATE_2= 1;
static int STATE_3= 2;
};
class Derived : public Base
{
static int STATE_4= 3;
};
No, C++ does not allow this sort of thing. Base::Color is a completely separate type from Derived::Color, with zero connection to them. This is no different from any other nested types; nested types defined in a base class are not connected to nested types defined in a derived class.
Nor can enumerations be inherited from one another.
This sort of things tends to go against good OOP practices anyway. After all, if a derived class introduces a new enumerator, how would the base class handle it? How would different derived class instances handle it?
If Base defines an operation over an enumeration, then Base defines the totality of the enumeration it operates on, and every class derived from it ought to be able to handle all of those options. Otherwise, something is very wrong with your virtual interface.
Why not just using namespaces to group enums?
namespace my_codes {
enum class color { red, green, blue } ;
enum class origin { server, client } ;
} // my_codes
Usage might be
struct my_signal {
my_codes::color flag ;
my_codes::origin source ;
} ;
But beware: "overkill is my biggest fear..." :) I would not enjoy some deep hierarchy of namespaces with enums in them and a such ...

c++ 11 =default keyword on virtual function for specifying default pure implementation

I am curious why, in C++ 11, use of "= default" on a derived virtual method does not select the pure base class implementation.
For example, the following test code produces the message "error: 'virtual void B::tst()' cannot be defaulted" from "g++ -std=c++11".
struct A {
virtual ~A () = default;
virtual void tst () = 0;
};
void A :: tst () {}
struct B : public A {
virtual void tst () = default;
};
We can of course provide a B::tst that invokes the default base implementation, but one is concerned that this might be the higher overhead implementation compared to a hypothetical "= default" based coding.
Sorry to ask questions about what might or might not be within the minds of the c++ standards committee persons, but nevertheless perhaps someone here at stack overflow will have some wisdom concerning the impracticality of using the default keyword in this way that would be interesting to hear.
Thanks!
According to the standard §8.4.2/p1 Explicitly-defaulted functions [dcl.fct.def.default] (Emphasis Mine):
A function definition of the form:
attribute-specifier-seqopt decl-specifier-seqopt declarator
virt-specifier-seqopt = default;
is called an explicitly-defaulted definition. A function that is
explicitly defaulted shall
(1.1) — be a special member function,
(1.2) — have the same declared function type (except for possibly differing ref-qualifiers and except that in
the case of a copy constructor or copy assignment operator, the parameter type may be “reference to
non-const T”, where T is the name of the member function’s class) as if it had been implicitly declared,
and
(1.3) — not have default arguments
Member function tst() is not a special member function. Thus, it cannot be defaulted.
Now specifying a member function of a class (e.g., class A) as pure virtual entails that any class that inherits from that class and you don't wan't it to be abstract as well must override that member function.

Cplex C++ interface. How to clean up memory?

Background: The C++ interface of IBM ILOG Cplex allocates and de-allocates memory rather unconventionally:
A declaration of an ILO environment IloEnv environment;, followed by a construction of models and solvers within this environment, followed by all these objects (including the environment) going out of scope results in a memory leak. Note that I have not used the new operator. One way to avoid this is to call environment.end(); before the object goes out of scope.
Setting: Now, I have a class whose purpose is to solve a specific ILP. This class has some member variables:
IloEnv ilpEnvironment_;
IloObjective ilpObjective_;
IloExpr ilpExpression_;
IloModel ilpModel_;
IloCplex ilpSolver_;
IloNumArray ilpSolution_;
IloNumVarArray ilpVariables_;
IloNumArray ilpStartValues_;
IloRangeArray constraints_;
These member variables are initialized in the initializer list of the constructor:
inline MyClass::MyClass()
: ilpEnvironment_(),
ilpObjective_(ilpEnvironment_),
ilpExpression_(ilpEnvironment_),
ilpModel_(ilpEnvironment_),
ilpSolver_(ilpModel_),
ilpSolution_(ilpEnvironment_),
ilpVariables_(ilpEnvironment_),
ilpStartValues_(ilpEnvironment_),
constraints_(ilpEnvironment_)
{ /* ... */ }
The destructor de-allocates all the memory (that has been allocated by member functions of the class that operate on the member variables):
inline MyClass::~MyClass() {
ilpEnvironment_.end();
}
Question: How do i implement a member function void clear() that de-allocates the memory and puts the class back into its initial state? Here are two rather naive attempts I made that don't work:
inline void MyClass::clear() {
ilpEnvironment_.end();
ilpEnvironment_ = IloEnv(); // does not work, whether or not I comment this line out
ilpObjective_ = IloObjective(ilpEnvironment_);
ilpExpression_ = IloExpr(ilpEnvironment_);
ilpModel_ = IloModel(ilpEnvironment_);
ilpSolver_ = IloCplex(ilpEnvironment_);
ilpSolution_ = IloNumArray(ilpEnvironment_);
ilpVariables_ = IloNumVarArray(ilpEnvironment_);
ilpStartValues_ = IloNumArray(ilpEnvironment_);
constraints_ = IloRangeArray(ilpEnvironment_);
}
If the purpose of the class is to solve a specific ILP model, then I would initialize the class with the model size/parameters, and create and destroy the CPLEX objects within a solve() member function while saving only the results as class members. Class members would be model parameters, and the object would keep all CPLEX dealings hidden.
You could even have a class member that keeps track of which constraints to activate in that particular solve() call.
If you absolutely have to use the CPLEX objects as changeable class members, then you might want to try to use object pointers as class members instead of the objects themselves. Calling IloEnv::end() destroys the objects associated with it, so you could call IloEnd::end() and then reassign the pointers to new objects.

Resources