Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does constructor affect performance?

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?

like image 563
user2726263 Avatar asked Aug 28 '13 16:08

user2726263


People also ask

What is the importance of constructor?

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.

What happens if constructor fails?

[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.

What should not be in a constructor?

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 !

Why constructor is used instead of function?

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.


1 Answers

The initialization will likely incur a small cost. However:

  1. The compiler might be able to eliminate the initializations if it can prove that they are unnecessary.

  2. 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.

  3. It gives you the reassurance of knowing that the three fields will always get initialized, thereby eliminating some types of potential bugs.

like image 58
NPE Avatar answered Sep 28 '22 09:09

NPE