Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why constructor is used instead of functions?

This is a very basic question, I searched it but i just want to ask this community that we have both constructors and methods. But normally we use constructor to initialize the variables instead of the methods. I think that both can be used to initialize variables. So what is the basic difference between both. Is there any solid reason? this is a very basic question so bear it for sake of beginner level. thanks in advance..

like image 460
Rafay Zia Mir Avatar asked Mar 17 '12 18:03

Rafay Zia Mir


People also ask

What is the advantage of using constructor over normal member functions?

One of the benefits of using a constructor over a method is that you can be assured the constructor was called and the work within the constructor was performed. The language specifies that to construct an object a constructor must be called.

Why do we use constructors instead of methods in Java?

Constructor in java is used to create the instance of the class. Constructors are almost similar to methods except for two things - its name is the same as the class name and it has no return type. Sometimes constructors are also referred to as special methods to initialize an object.

What is special about the constructor as compared to other functions?

A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. An ordinary member function has its own name, a return type (which may be void), and is invoked using the dot operator.


3 Answers

The most important difference: When you instantiate an object it's constructor will be invoked whereas calling a method is always optional. You therefore might forget to call your initialization method and fail to initialize everything correctly.

For example, all these normal ways of instantiating an object will call the constructor

Foo* p = new Foo();
Foo p;

Or if you have mandatory arguments, don't define a default constructor and instead require construction with parameters:

class Foo
{
private:
   Foo();
public:
   Foo(int param1, double param2)
};

This has the advantage of requiring the arguments before you even instantiate the class. So you're forced to do:

Foo* p = new Foo(1, 5.0);

and failing to construct with valid arguments becomes a compiler error:

Foo* p = new Foo(); // compiler error

So whenever possible, always err on the side of doing your initialization in a constructor. There are a few cases where a constructor might not be viable. For example, the only way to fail a constructor is by using an exception. The failure to construct may be "routine" and not truly exceptional. Also exceptions might be expensive on some architectures. Another case might be when you want to ensure that virtual methods are fully bound, which is guaranteed to be true only after construction.

like image 177
Doug T. Avatar answered Oct 15 '22 17:10

Doug T.


They can't both be used to initialize member variables. It is the job of the constructor to initialize members, and it is called automatically whenever you create a new instance.

Consider the following:

class Foo {
public:
    // Constructor
    Foo() : x(53)   // Initialise x
    {}

    void bar() {
        x = 42;     // Error, attempt to *assign* a const member!
    }

private:
    const int x;
};

Without the constructor, there would be no way to initialise member x.

like image 42
Oliver Charlesworth Avatar answered Oct 15 '22 16:10

Oliver Charlesworth


Constructors are called automatically, so there's no need to worry whether the user has invoked an initialization method yet. However, the Google style guide does have something to say about constructors:

  • There is no easy way for constructors to signal errors, short of using exceptions.
  • If the work fails, we now have an object whose initialization code failed, so it may be an indeterminate state.
  • If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce this problem even if your class is not currently subclassed, causing much confusion.
  • If someone creates a global variable of this type, the constructor code will be called before main(), possibly breaking some implicit assumptions in the constructor code.

Google's recommendation is to have straightforward initiation in a constructor, and non-trivial initiation in a separate method.

like image 1
chrisaycock Avatar answered Oct 15 '22 15:10

chrisaycock