I have class with 3 member variables declared as public, I can initially it explicitly anywhere in code, still I have written constructor with initial values does this constructor affect performance overhead?
class ABC{
public:
int a;
int b;
int c;
ABC (): a(0) , b(0), c(0)
{
}
};
Please let me know if constructor add performance overhead?
Importance of constructors Constructors are used to initialize the objects of the class with initial values. Constructors are invoked automatically when the objects are created. Constructors can have default parameters. If constructor is not declared for a class , the C++ compiler generates a default constructor.
[17.8] How can I handle a constructor that fails? Throw an exception. Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.
The most common mistake to do in a constructor as well as in a destructor, is to use polymorphism. Polymorphism often does not work in constructors !
Constructors can be used for efficient memory management, which is not possible with functions. Destructor can be used to destroy the constructors when not needed. Moreover, the use of copy constructor is known to prevent difficulties or errors due to memory mis happenings.
The initialization will likely incur a small cost. However:
The compiler might be able to eliminate the initializations if it can prove that they are unnecessary.
Even if there is a small cost, it is overwhelmingly likely that it is completely irrelevant in the context of the overall application. You could use a profiler to quantify the performance effect.
It gives you the reassurance of knowing that the three fields will always get initialized, thereby eliminating some types of potential bugs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With