Calling member functions from a constructor - c++

I know this question has a similar title to this: C++: calling member functions within constructor? but I am asking a more general question.
Is it good practice to call member functions from within a constructor? It makes reading the code easier and I prefer the encapsulation type way of doing it (ie. each block of code has a single objective).
An illustrative example, in python:
class TestClass:
def __init__(self):
self.validate()
def validate(self):
# this validates some data stored in the class
Is this a better way of doing it than writing the validate code inside the constructor? Are there drawbacks to this method? For example is it more costly with the function overhead?
I personally prefer it for readability but that's just my preference.
Cheers

I don't think there is anything inherently wrong in calling member functions from a constructor provided that they are not virtual functions.
The problem with calling virtual member functions from a constructor is that a subclass can override the function. This will cause the constructor to call the overridden implementation in the subclass, before the constructor for the subclass part of the object has been called.
In Java, any one of the private, static or final access modifiers will make the method safe to call from a constructor by preventing a virtual call to the superclass method. I don't think these techniques are available in Python.

There is at least one associated "gotcha" you should be aware of:
N3797 12.6.2/14
Member functions (including virtual member functions, 10.3) can be called for an object under construction. Similarly, an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the result
of the operation is undefined. [Example:
class A {
public:
A(int);
};
class B : public A {
int j;
public:
int f();
B() : A(f()), // undefined: calls member function
// but base A not yet initialized
j(f()) { } // well-defined: bases are all initialized
};
class C {
public:
C(int);
};
class D : public B, C {
int i;
public:
D() : C(f()), // undefined: calls member function
// but base C not yet initialized
i(f()) { } // well-defined: bases are all initialized
};
— end example]

The main problem with this is that the member function has to work with an object that may be only partially initialized. And if it (even accidentally) passes a reference to the object somewhere else, other code has to od the same. This can get pretty confusing and error-prone, especially once you start overriding such a function in a subclass.
So in general, this practice should be avoided or at least confined to functions that can't be overriden, and they should never pass a reference to the object being constructed to any other code.

I'm more familiar with C++ than Python, but I see no problem with calling member functions from constructors, especially when this practice is able to factor out similar code from multiple constructors. Anything that reduces redundancy is good in my books.

From a readability point of view it is definitely better. One thing you might have to ask yourself here though is whether the validate method is allowed to run after the object is initialized. If that is not the case, you can a) use some kind of private initialized variable or b) use the Builder pattern to get your objects into a valid state before using them.
Make sure the function is private. You do not want to mess with subclasses overriding it (Unless this is desired by design, in which case make it abstract/virtual).

first, this member function cannnot be virtural function,
second, this member function must be implemented in the same file, if you declare it in *.h, then implement it in *.cpp, gcc/clang will report this error undefined reference to

Related

Prevent pointer reassignment

I am reading Effective C++ Third Edition by Scott Meyers.
He says generally it is not a good idea to inherit from classes that do not contain virtual functions because of the possibility of undefined behavior if you somehow convert a pointer of a derived class into the pointer of a base class and then delete it.
This is the (contrived) example he gives:
class SpecialString: public std::string{
// ...
}
SpecialString *pss = new SpecialString("Impending Doom");
std::string *ps;
ps = pss;
delete ps; // undefined! SpecialString destructor won't be called
I understand why this results in error, but is there nothing that can be done inside the SpecialString class to prevent something like ps = pss from happening?
Meyers points out (in a different part of the book) that a common technique to explicitly prevent some behavior from being allowed in a class is to declare a specific function but intentionally don't define it. The example he gave was copy-construction. E.g. for classes that you don't want to allow copy-construction to be allowed, declare a private copy constructor but do not define it, thus any attempts to use it will result in compile time error.
I realize ps = pss in this example is not copy construction, just wondering if anything can be done here to explicitly prevent this from happening (other than the answer of "just don't do that").
The language allows implicit pointer conversions from a pointer to a derived class to a pointer to its base class, as long as the base class is accessible and not ambiguous. This is not something that can be overridden by user code. Furthermore, if the base class allows destruction, then once you've converted a pointer-to-derived to a pointer-to-base, you can delete the base class via the pointer, leading to the undefined behavior. This cannot be overridden by a derived class.
Hence you should not derive from classes that were not designed to be base classes. The lack of workarounds in your book is indicative of the lack of workarounds.
There are two points in the above that might be worth taking a second look at. First: "as long as the base class is accessible and not ambiguous". (I'd rather not get into the "ambiguous" point.) You can prevent casting a pointer-to-derived to a pointer-to-base in code outside your class implementation by making the base class private. If you do that, though, you should take some time to think about why you are inheriting in the first place. Private inheritance is typically rare. Often it would make more sense (or at least as much sense) to not derive from the other class and instead have a data member whose type is the other class.
Second: "if the base class allows destruction". This does not apply in your example where you cannot change the base class definition, but it does apply to the claim "generally it is not a good idea to inherit from classes that do not contain virtual [destructors]". There is another viable option. It may be reasonable to inherit from a class that has no virtual functions if the destructor of that class is protected. If the destructor of a class is protected, then you are not allowed to use delete on a pointer to that class (outside the implementations of the class and classes derived from it). So you avoid the undefined behavior as long as the base class has either a virtual destructor or a protected one.
There's two approaches that might make sense:
If the real problem is that string is not really meant to be derived from and you have control over it - then you could make it final. (Obviously not something you can do with your std::string though, since you dont control std::string)
If string is OK to derive from, but not to use polymorphically, you can remove the new and delete functions from SpecialString to prevent allocating one via new.
For example:
#include <string>
class SpecialString : std::string {
void* operator new(size_t size)=delete;
};
int main() {
SpecialString ok;
SpecialString* not_ok = new SpecialString();
}
fails to compile with:
code.cpp:9:27: error: call to deleted function 'operator new'
SpecialString* not_ok = new SpecialString();
^
code.cpp:4:9: note: candidate function has been explicitly deleted
void* operator new(size_t size)=delete;
Note this doesn't stop odd behaviour like:
SpecialString ok;
std::string * ok_p = &ok;
ok_p->something();
which will always call std::string::something, not SpecialString::something if you've provided one. Which may not be what you expect.
You don't have to check this in runtime if you prevent the error.
As your book says it is a good practice to use a virtual destructor in the base class (with implementation), and of course a destructor for the derived class, this way if you assign a pointer to the derived class - to the base class, it first gets destroyed as a base, and then as a derived object.
you can see an example here https://www.geeksforgeeks.org/virtual-destructor
see comment for more specific clarification

Can virtual function be called inside member initializer lists?

effective c++ item 9
Can function createLogString be virtual?
class BuyTransaction: public Transaction {
 public:
  BuyTransaction( parameters ):Transaction(createLogString(parameters)) { ... }
  ...
 private:
  static std::string createLogString( parameters );
};
Yes, it can be virtual (instead of static). It will still be statically bound during construction however, and not dispatched dynamically.
The only point to making it virtual is if it is also used in some other member of the class (that is not a constructor/destructor) and a deriving class can possibly override it to do something useful for those members. However, that starts having the faint traces of a design smell.
Scott's advice of "Never call virtual functions during construction or destruction" stems from the fact that it rarely if ever accomplishes anything useful.

how functions of a not fully constructed objects are called?

creating an object using a constructor and along with that calling functions of object which is being constructed:
class A
{
public:
A()
{
this->show();
}
void show()
{
cout<<"show called!";
}
};
and now i m creating object in main() as below:
int main()
{
A a;
int xy;
cin>>xy;
return 0;
}
my doubt is that when i am creating an object using constructor then how i am able to call object function while object is not fully constructed?
virtual function calls:
class A
{
public:
A()
{
}
virtual void show()
{
cout<<"show called!";
}
};
class B:public A
{
public:
B()
{
A *a=this;
a->show();
}
void show()
{
cout<<"derived show";
}
};
int main()
{
A a;
B b;
int xy;
cin>>xy;
return 0;
}
working fine with output: derived show
It's fine to call virtual functions and non-static member functions:
See section 12.7 of http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf:
4 Member functions, including virtual functions (10.3), can be called
during construction or destruction (12.6.2).
However when using virtual functions in a constructor there are some restrictions. It's a bit of a mouthful:
When a virtual function is called directly or indirectly from a
constructor (including the mem-initializer or
brace-or-equal-initializer for a non-static data member) or from a
destructor, and the object to which the call applies is the object
under construction or destruction, the function called is the one
defined in the constructor or destructor’s own class or in one of its
bases, but not a function overriding it in a class derived from the
constructor or destructor’s class, or overriding it in one of the
other base classes of the most derived object (1.8).
I interpret the above paragraph as saying the virtual functions called will not be in any derived class. This makes sense because at this point in the execution phase any constructor in a derived class will not have begun execution.
Additionally part 1 places a restriction that use of non-static members should occur after the construction begins. In your example the members are being invoked after the construction begins, so you're not violating part 1:
1 For an object with a non-trivial constructor, referring to any
non-static member or base class of the object before the constructor
begins execution results in undefined behavior.
This code is completely legal. You can call methods
in the class constructor.
All constants (from the initialization list) are already initialized and all base class constructors are called.
However, You should not call virtual methods in the constructor. See Scott Meyers explanation for this restriction.
The thing to think about is, which parts of the object are constructed at the time when you call show()?
Since you call show() from within your constructor's body (and not e.g. from within the constructor's initializer list) you can rest assured that all of the A object's member variables have already been constructed (since that happens before the constructor body is executed).
What might trip you up would be if show() was a virtual method, and A::A() was being called from the constructor of a subclass of A. In that case, you might want show() to call B::show(), but that won't happen because the vtable for B hasn't been set up yet (you would end up calling A::show() instead, or crashing the program if A::show() was a pure-virtual method)
You are calling a function in an partially constructed object, which may result in erroneous behavior if such function deals with class members and such. I am not sure whether its invoking undefined behaviour or not, but I don't think its a good practice. And the situation gets worse with inheritance and virtual functions!
In your example, show could be declared static and there will be no risk in calling it.
Consider a class as 2 separate parts: The object containing fields (variables) and the methods (functions). The methods of a given class exist independent of any particular instance, so it can be called at any time by a valid instance, even mid-construction.
The fields are "created" when the object is instantiated, before the constructor is run. However, they have no values set to them. So, if your constructor calls any methods BEFORE the fields are initialised to sensible values, then you're going to experience some undefined behaviour.
Whenever possible, if you must call a method inside a constructor, be sure to initialise as many fields as possible to sensible values.
my doubt is that when i am creating an object using constructor then how i am able to call object function while object is not fully constructed?
what happens in your example is fine, as long as you initialize where you are supposed to (the initialization list). you are using static dispatch on an object which has initialized members (specifically, A has no such variables to initialize).
what then is invalid?
not initializing your members correctly, or using them before they are really initialized. favor the initialization list without using this.
using dynamic dispatch from within your constructor's body (or initializer). your object is not fully constructed.
unusually, you could also attempt to typecast it to a subclass from the constructor.

Is calling pure virtual functions indirectly from a constructor always undefined behaviour?

I'm working on building Cppcheck on AIX with the xlC compiler (see previous question). Checker classes all derive from a Check class, whose constructor registers each object in a global list:
check.h
class Check {
public:
Check() {
instances().push_back(this);
instances().sort();
}
static std::list<Check *> &instances();
virtual std::string name() const = 0;
private:
bool operator<(const Check *other) const {
return (name() < other->name());
}
};
checkbufferoverrun.h
class CheckBufferOverrun: public Check {
public:
// ...
std::string name() const {
return "Bounds checking";
}
};
The problem I appear to be having is with the instances().sort() call. sort() will call Check::operator<() which calls Check::name() on each pointer in the static instances() list, but the Check instance that was just added to the list has not yet had its constructor fully run (because it's still inside Check::Check()). Therefore, it should be undefined behaviour to call ->name() on such a pointer before the CheckBufferOverrun constructor has completed.
Is this really undefined behaviour, or am I missing a subtlety here?
Note that I don't think the call to sort() is strictly required, but the effect is that Cppcheck runs all its checkers in a deterministic order. This only affects the output in the order in which errors are detected, which causes causes some test cases to fail because they're expecting the output in a particular order.
Update: The question as above still (mostly) stands. However, I think the real reason why the call to sort() in the constructor wasn't causing problems (ie. crashing by calling a pure virtual function) is that the Check::operator<(const Check *) is never actually called by sort()! Rather, sort() appears to compare the pointers instead. This happens in both g++ and xlC, indicating a problem with the Cppcheck code itself.
Yes, it's undefined. The standard specifically says so in 10.4/6
Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined.
It is true that calling a pure virtual function from a constructor is always an undefined behaviour.
The virtual pointer can not be assumed to be set until the constructor has run completely (closing "}"), and hence any call to a virtual function (or pure virtual function) has to be setup at the time of compilation itself (statically bound call).
Now, if the virtual function is pure virtual function, the compiler will generally insert its own implementation for such pure virtual function, the default behavior of which is to generate a segmentation fault. The Standard does not dictate what should be the implementation of a pure virtual function, but most of C++ compilers adopt aforesaid style.
If your code is not causing any runtime mischief demeanour, then it is not getting called in the said call sequence. If you could post the implementation code for below 2 functions
instances().push_back(this);
instances().sort();
then maybe it will help to see what's going on.
As long as object construction isn't finished, a pure virtual function may not be called. However, if it's declared pure virtual in a base class A, then defined in B (derived from A), the constructor of C (derived from B) may call it, since B's construction is complete.
In your case, use a static constructor instead:
class check {
private Check () { ... }
public:
static Check* createInstance() {
Check* check = new Check();
instances().push_back(check);
instances().sort();
}
...
}
I think your real problem is that you've conflated two things: the Checker base class, and some mechanism for registering (derived) instances of Check.
Among other things, this isn't particularly robust: I may want to use your Checker classes, but I may want to register them differently.
Maybe you could do something like this: Checker get a protected ctor (it's abstract anyway, and so only derived classes ought to be calling the Checker ctor).
Derived classes also have protected ctors, and a public static method (the "named constructor pattern") to create instances. That creating method news up a Checker subclass, and them passes it (fully created at this point) to a CheckerRegister class (which is also abstract, so users can implemented their own if need be).
You use whatever singleton pattern, or dependency injection mechanism, that you prefer, to instantiate a Checkerregister and make it available to Checker subclasses.
One simple way to do this would be to have a getCheckerRegister static method on Checker.
So a Checker subclass might look like this:
class CheckBufferOverrun: public Check {
protected:
CheckBufferOverrun : Check("Bounds checking") {
// since every derived has a name, why not just pass it as an arg?
}
public:
CheckBufferOverrun makeCheckBufferOverrun() {
CheckBufferOverrun that = new CheckBufferOverrun();
// get the singleton, pass it something fully constructed
Checker.getCheckerRegister.register(that) ;
return that;
}
If it looks like this will end up being a lot of boilerplate code, write a template. If you worry that because each template instance in C++ is a real and unique class, write a non-templated base class that will register any Checker-derived.

Why do we not have a virtual constructor in C++?

Why does C++ not have a virtual constructor?
Hear it from the horse's mouth. :)
From Bjarne Stroustrup's C++ Style and Technique FAQ Why don't we have virtual constructors?
A virtual call is a mechanism to get work done given partial
information. In particular, "virtual" allows us to call a function
knowing only any interfaces and not the exact type of the object. To
create an object you need complete information. In particular, you
need to know the exact type of what you want to create. Consequently,
a "call to a constructor" cannot be virtual.
The FAQ entry goes on to give the code for a way to achieve this end without a virtual constructor.
Virtual functions basically provide polymorphic behavior. That is, when you work with an object whose dynamic type is different than the static (compile time) type with which it is referred to, it provides behavior that is appropriate for the actual type of object instead of the static type of the object.
Now try to apply that sort of behavior to a constructor. When you construct an object the static type is always the same as the actual object type since:
To construct an object, a constructor needs the exact type of the object it is to create [...] Furthermore [...]you cannot have a pointer to a constructor
(Bjarne Stroustup (P424 The C++ Programming Language SE))
Unlike object oriented languages such as Smalltalk or Python, where the constructor is a virtual method of the object representing the class (which means you don't need the GoF abstract factory pattern, as you can pass the object representing the class around instead of making your own), C++ is a class based language, and does not have objects representing any of the language's constructs. The class does not exist as an object at runtime, so you can't call a virtual method on it.
This fits with the 'you don't pay for what you don't use' philosophy, though every large C++ project I've seen has ended up implementing some form of abstract factory or reflection.
two reasons I can think of:
Technical reason
The object exists only after the constructor ends.In order for the constructor to be dispatched using the virtual table , there has to be an existing object with a pointer to the virtual table , but how can a pointer to the virtual table exist if the object still doesn't exist? :)
Logic reason
You use the virtual keyword when you want to declare a somewhat polymorphic behaviour. But there is nothing polymorphic with constructors , constructors job in C++ is to simply put an object data on the memory . Since virtual tables (and polymorphism in general) are all about polymorphic behaviour rather on polymorphic data , There is no sense with declaring a virtual constructor.
Summary: the C++ Standard could specify a notation and behaviour for "virtual constructor"s that's reasonably intuitive and not too hard for compilers to support, but why make a Standard change for this specifically when the functionality can already be cleanly implemented using create() / clone() (see below)? It's not nearly as useful as many other language proposal in the pipeline.
Discussion
Let's postulate a "virtual constructor" mechanism:
Base* p = new Derived(...);
Base* p2 = new p->Base(); // possible syntax???
In the above, the first line constructs a Derived object, so *p's virtual dispatch table can reasonably supply a "virtual constructor" for use in the second line. (Dozens of answers on this page stating "the object doesn't yet exist so virtual construction is impossible" are unnecessarily myopically focused on the to-be-constructed object.)
The second line postulates the notation new p->Base() to request dynamic allocation and default construction of another Derived object.
Notes:
the compiler must orchestrate memory allocation before calling the constructor - constructors normally support automatic (informally "stack") allocation, static (for global/namespace scope and class-/function-static objects), and dynamic (informally "heap") when new is used
the size of object to be constructed by p->Base() can't generally be known at compile-time, so dynamic allocation is the only approach that makes sense
it is possible to allocate runtime-specified amounts of memory on the stack - e.g. GCC's variable-length array extension, alloca() - but leads to significant inefficiencies and complexities (e.g. here and here respectively)
for dynamic allocation it must return a pointer so memory can be deleted later.
the postulated notation explicitly lists new to emphasise dynamic allocation and the pointer result type.
The compiler would need to:
find out how much memory Derived needed, either by calling an implicit virtual sizeof function or having such information available via RTTI
call operator new(size_t) to allocate memory
invoke Derived() with placement new.
OR
create an extra vtable entry for a function that combines dynamic allocation and construction
So - it doesn't seem insurmountable to specify and implement virtual constructors, but the million-dollar question is: how would it be better than what's possible using existing C++ language features...? Personally, I see no benefit over the solution below.
`clone()` and `create()`
The C++ FAQ documents a "virtual constructor" idiom, containing virtual create() and clone() methods to default-construct or copy-construct a new dynamically-allocated object:
class Shape {
public:
virtual ~Shape() { } // A virtual destructor
virtual void draw() = 0; // A pure virtual function
virtual void move() = 0;
// ...
virtual Shape* clone() const = 0; // Uses the copy constructor
virtual Shape* create() const = 0; // Uses the default constructor
};
class Circle : public Shape {
public:
Circle* clone() const; // Covariant Return Types; see below
Circle* create() const; // Covariant Return Types; see below
// ...
};
Circle* Circle::clone() const { return new Circle(*this); }
Circle* Circle::create() const { return new Circle(); }
It's also possible to change or overload create() to accept arguments, though to match the base class / interface's virtual function signature, arguments to overrides must exactly match one of the base class overloads. With these explicit user-provided facilities, it's easy to add logging, instrumentation, alter memory allocation etc..
We do, it's just not a constructor :-)
struct A {
virtual ~A() {}
virtual A * Clone() { return new A; }
};
struct B : public A {
virtual A * Clone() { return new B; }
};
int main() {
A * a1 = new B;
A * a2 = a1->Clone(); // virtual construction
delete a2;
delete a1;
}
Semantic reasons aside, there is no vtable until after the object is constructed, thus making a virtual designation useless.
Virtual functions in C++ are an implementation of run-time polymorphism, and they will do function overriding. Generally the virtual keyword is used in C++ when you need dynamic behavior. It will work only when object exists. Whereas constructors are used to create the objects. Constructors will be called at the time of object creation.
So if you create the constructor as virtual, as per the virtual keyword definition, it should have existing object to use, but constructor is used to to create the object, so this case will never exist. So you should not use the constructor as virtual.
So, if we try to declare virtual constructor compiler throw an Error:
Constructors cannot be declared virtual
You can find an example and the technical reason to why it is not allowed in #stefan 's answer. Now a logical answer to this question according to me is:
The major use of virtual keyword is to enable polymorphic behaviour when we don't know what type of the object the base class pointer will point to.
But think of this is more primitive way, for using virtual functionality you will require a pointer. And what does a pointer require? An object to point to! (considering case for correct execution of the program)
So, we basically require an object that already exists somewhere in the memory (we are not concerned with how the memory was allocated, it may be at compile time or either runtime) so that our pointer can correctly point to that object.
Now, think of the situation about the moment when the object of the class to be pointed is being assigned some memory -> Its constructor will be called automatically at that instance itself!
So we can see that we don't actually need to worry about the constructor being virtual, because in any of the cases you wish to use a polymorphic behaviour our constructor would have already been executed making our object ready for usage!
When people ask a question like this, I like to think to myself "what would happen if this were actually possible?" I don't really know what this would mean, but I guess it would have something to do with being able to override the constructor implementation based on the dynamic type of the object being created.
I see a number of potential problems with this. For one thing, the derived class will not be fully constructed at the time the virtual constructor is called, so there are potential issues with the implementation.
Secondly, what would happen in the case of multiple inheritance? Your virtual constructor would be called multiple times presumably, you would then need to have some way of know which one was being called.
Thirdly, generally speaking at the time of construction, the object does not have the virtual table fully constructed, this means it would require a large change to the language specification to allow for the fact that the dynamic type of the object would be known at construction time. This would then allow the base class constructor to maybe call other virtual functions at construction time, with a not fully constructed dynamic class type.
Finally, as someone else has pointed out you can implement a kind of virtual constructor using static "create" or "init" type functions that basically do the same thing as a virtual constructor would do.
Although the concept of virtual constructors does not fit in well since object type is pre-requisite for object creation, its not completly over-ruled.
GOF's 'factory method' design pattern makes use of the 'concept' of virtual constructor, which is handly in certain design situations.
Virtual functions are used in order to invoke functions based on the type of object pointed to by the pointer, and not the type of pointer itself. But a constructor is not "invoked". It is called only once when an object is declared. So, a constructor cannot be made virtual in C++.
Interview answer is : virtual ptr and table are related to objects but not the class.hence constructor builds the virtual table
hence we cant have virtual constructor as there is no Vtable before obj creation.
You shouldn't call virtual function within your constructor either. See : http://www.artima.com/cppsource/nevercall.html
In addition I'm not sure that you really need a virtual constructor. You can achieve polymorphic construction without it: you can write a function that will construct your object according to the needed parameters.
A virtual-table(vtable) is made for each Class having one or more 'virtual-functions'. Whenever an Object is created of such class, it contains a 'virtual-pointer' which points to the base of corresponding vtable. Whenever there is a virtual function call, the vtable is used to resolve to the function address.
Constructor can not be virtual, because when constructor of a class is executed there is no vtable in the memory, means no virtual pointer defined yet. Hence the constructor should always be non-virtual.
Cant we simply say it like.. We cannot inherit constructors. So there is no point declaring them virtual because the virtual provides polymorphism .
The virtual mechanism only works when you have a based class pointer to a derived class object. Construction has it's own rules for the calling of base class constructors, basically base class to derived. How could a virtual constructor be useful or called? I don't know what other languages do, but I can't see how a virtual constructor could be useful or even implemented. Construction needs to have taken place for the virtual mechanism to make any sense and construction also needs to have taken place for the vtable structures to have been created which provides the mechanics of the polymorphic behaviour.
C++ virtual constructor is not possible.For example you can not mark a constructor as virtual.Try this code
#include<iostream.h>
using namespace std;
class aClass
{
public:
virtual aClass()
{
}
};
int main()
{
aClass a;
}
It causes an error.This code is trying to declare a constructor as virtual.
Now let us try to understand why we use virtual keyword. Virtual keyword is used to provide run time polymorphism. For example try this code.
#include<iostream.h>
using namespace std;
class aClass
{
public:
aClass()
{
cout<<"aClass contructor\n";
}
~aClass()
{
cout<<"aClass destructor\n";
}
};
class anotherClass:public aClass
{
public:
anotherClass()
{
cout<<"anotherClass Constructor\n";
}
~anotherClass()
{
cout<<"anotherClass destructor\n";
}
};
int main()
{
aClass* a;
a=new anotherClass;
delete a;
getchar();
}
In main a=new anotherClass; allocates a memory for anotherClass in a pointer a declared as type of aClass.This causes both the constructor (In aClass and anotherClass) to call automatically.So we do not need to mark constructor as virtual.Because when an object is created it must follow the chain of creation (i.e first the base and then the derived classes).
But when we try to delete a delete a; it causes to call only the base destructor.So we have to handle the destructor using virtual keyword. So virtual constructor is not possible but virtual destructor is.Thanks
There's a very basic reason: Constructors are effectively static functions, and in C++ no static function can be virtual.
If you have much experience with C++, you know all about the difference between static & member functions. Static functions are associated with the CLASS, not the objects (instances), so they don't see a "this" pointer. Only member functions can be virtual, because the vtable- the hidden table of function pointers that makes 'virtual' work- is really a data member of each object.
Now, what is the constructor's job? It is in the name- a "T" constructor initializes T objects as they're allocated. This automatically precludes it being a member function! An object has to EXIST before it has a "this" pointer and thus a vtable. That means that even if the language treated constructors as ordinary functions (it doesn't, for related reasons I won't get into), they'd have to be static member functions.
A great way to see this is to look at the "Factory" pattern, especially factory functions. They do what you're after, and you'll notice that if class T has a factory method, it is ALWAYS STATIC. It has to be.
If you think logically about how constructors work and what the meaning/usage of a virtual function is in C++ then you will realise that a virtual constructor would be meaningless in C++. Declaring something virtual in C++ means that it can be overridden by a sub-class of the current class, however the constructor is called when the objected is created, at that time you cannot be creating a sub-class of the class, you must be creating the class so there would never be any need to declare a constructor virtual.
And another reason is, the constructors have the same name as its class name and if we declare constructor as virtual, then it should be redefined in its derived class with the same name, but you can not have the same name of two classes. So it is not possible to have a virtual constructor.
When a constructor is invoked, although there is no object created till that point, we still know the kind of object that is gonna be created because the specific constructor of the class to which the object belongs to has already been called.
Virtual keyword associated with a function means the function of a particular object type is gonna be called.
So, my thinking says that there is no need to make the virtual constructor because already the desired constructor whose object is gonna be created has been invoked and making constructor virtual is just a redundant thing to do because the object-specific constructor has already been invoked and this is same as calling class-specific function which is achieved through the virtual keyword.
Although the inner implementation won’t allow virtual constructor for vptr and vtable related reasons.
Another reason is that C++ is a statically typed language and we need to know the type of a variable at compile-time.
The compiler must be aware of the class type to create the object. The type of object to be created is a compile-time decision.
If we make the constructor virtual then it means that we don’t need to know the type of the object at compile-time(that’s what virtual function provide. We don’t need to know the actual object and just need the base pointer to point an actual object call the pointed object’s virtual functions without knowing the type of the object) and if we don’t know the type of the object at compile time then it is against the statically typed languages. And hence, run-time polymorphism cannot be achieved.
Hence, Constructor won’t be called without knowing the type of the object at compile-time. And so the idea of making a virtual constructor fails.
"A constructor can not be virtual"
there are some valid reasons that justify this statement.
to create an object the constructor of the object class must be of the same type as the class. But, this is not possible with a virtually implemented constructor.
at the time of calling the constructor, the virtual table would not have been created to resolve any virtual function calls. Thus, a virtual constructor itself would not have anywhere to look up to.
As a result, it is not possible to declare a constructor to be virtual.
The Vpointer is created at the time of object creation. vpointer wont exists before object creation. so there is no point of making the constructor as virtual.