answersLogoWhite

0


Best Answer

A constructor is a special class method that instantiates an object of the class.

All objects must have at least two constructors, one of which must be a copy constructor. Even if you do not explicitly declare a copy constructor, one is generated for you with public access by the compiler. The purpose of the copy constructor is to instantiate new objects from existing objects. Even if you never explicitly call the copy constructor, it is automatically called whenever you pass an object to a function by value, as the object must be copied.

If you do not declare any constructors, then both the copy constructor and the default constructor are generated for you. The default constructor is a constructor that accepts no parameters, or that is declared with all default parameters.

Although the compiler will generate default and copy constructors for you, it is always recommended that you declare your own constructors, thus ensuring your object members are always correctly initialised and valid. An uninitialised object is a potential time-bomb.

Constructors are not functions; they do not return any value, not even void. The assignment operator (which does return a value) is not a constructor; it is used to initialise an existing object from another existing object -- it does not instantiate a new object.

Constructors are called whenever you instantiate a reference to an object, or allocate memory to an object using the new operator, or copy a new object from an existing object.

All constructors have the same name as the class itself. Construction overloads can be differentiated by their signature (the number and type of parameters they accept). The copy constructor is signified by the fact its only parameter is a constant reference to an object of the same class.

class Object

{

public:

Object(); // Default constructor (no parameters)

Object(const Object& object); // Copy constructor

Object(int x); // Overloaded constructor

}

As well as constructors, it is recommended you also declare your own assignment operator and destructor. Even if the compiler-generated versions are adequate for your needs, it costs nothing but a little time to declare your own. But if your class allocates dynamic memory on the heap, you must include code in the constructors, destructor and assignment operator to ensure that memory is correctly initialised and released, and that self-references are correctly accounted for; the compiler-generated methods will not do it for you.

User Avatar

Wiki User

11y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

13y ago

In a class, the Destructor is like the opposite of the Constructor. The Constructor is run when an object of the class is created (usually to set up the variables as needed), and the Destructor is run when it is destroyed (usually to clean up or delete variables).

This answer is:
User Avatar

User Avatar

Wiki User

15y ago

In C++, and in other object oriented languages such as JAVA or Smalltalk, a constructor is a method that runs when an instance of a class is created. It is responsible for initializing that instance, and placing it into a known state.

The destructor, on the other hand, runs when an instance of a class is destroyed. It is responsible for cleaning up or deleting things that got allocated during the class' lifetime.

Without explicit constructors and destructors, the compiler generates simple, default code to allocate, deallocate, and copy the class members as needed. This generally works, unless the member is a pointer to something else, such as an array, and that array needs to be allocated, copied, and/or deallocated.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

Class constructors (there may be more than one constructor per class, one of which must be a copy constructor) allows the programmer to control the initialisation of an object instantiated from a class, thus ensuring consistent initialisation regardless of which constructor is called.

The class destructor (there can be only one destructor per class) allows the programmer one final opportunity to release any memory allocated to the class members and to perform any last-minute operations before an object falls from scope.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

There are no problems with constructors or destructors in C++. Any problems encountered are a result of the code you write, not a result of the language.

Constructors exist purely to initialise an object in a consistent manner while destructors exist to allow an instance of a class to clean up any dynamic memory allocations. If you use them for any other purpose then there's a clear design flaw in your class.

This answer is:
User Avatar

User Avatar

Wiki User

12y ago

The constructor is a method that runs to initialize the instance of the class. It runs right after memory allocation. The destructor is a method that runs to deinitialize the instance of the class. If runs right before memory deallocation.

This answer is:
User Avatar

User Avatar

Wiki User

11y ago

A constructor is a class initialisation routine. Classes must have at least one constructor, but typically have two or more. It is important to note that constructors are not functions. Although they are declared much like a function, they cannot be called directly because they have no return value (not even NULL). Constructors are invoked automatically whenever an object of the class is instantiated.

Aside from the lack of a return value, constructors also differ from functions in that they have an implicit initialisation section that is invoked before the constructor's body is invoked. In many cases it is often more beneficial to explicitly define the initialisation section in order to ensure the most efficient construction occurs.

Let's examine the following simple class:

struct A {

int m_data;

};

We can also declare A as a class, but m_data must be declared public in order to match the struct definition:

class A {

public:

int m_data;

};

Other than the default member accessor (public for struct, private for class), struct and class behave exactly the same way, and both are known as classes (there is no concept of a C-style struct in C++ unless writing functions explicitly in C, in which case there are neither constructors nor methods). For the remainder of this answer, we will use struct.

Although we have not declared any constructors in our class, two constructors are implicitly declared for us by the compiler: a default constructor (one that has no arguments) and a copy constructor (where the first argument is a constant reference to an existing instance of the same class or one of its derivatives).

In order to see how these constructors are invoked, we must explicitly define them.

struct A {

A(const int=0); // default constructor

A(const A&); // copy constructor

int m_data; // member data

};

A::A(const int data=0) : m_data(data) {

std::cout<<"Default constructor"<<std::endl;

}

A::A(const A& a) : m_data(a.m_data) {

std::cout<<"Copy constructor"<<std::endl;

}

Note that the constructor body is used purely to provide a trace. The member data, A::m_data, is initialised through the initialisation section that immediately precedes the body of the constructor. If the class has more than one member datum, the data can be initialised using a comma-separated list of data members.

Note also that member data is initialised using construction syntax even if the member data is a primitive data type such as int. This becomes more relevant when the member data is another class of object, as it allows you to invoke a specific constructor.

If we now instantiate some objects from class A, we can see how and when constructors are invoked:

int main()

{

A a; // Invoke the default constructor (a.m_data=0).

A b(42); // Invoke the default constructor (b.m_data=42).

A c = 42; // invoke the default constructor (c.m_data=42).

A d(a); // Invoke the copy constructor (d.m_data=0).

A e = c; // Invoke the copy constructor (e.m_data=42).

A& f = e; // Refer to e (no construction required).

}

Note that f is a reference to an existing object, therefore no constructor is invoked. That is, f is an alternate name for e -- they are one and the same object.

In some cases it may not be possible to use the initialisation section to fully initialise a member. For instance, if we suppose that A::m_data must always be in the range 1 to 100, then we must handle cases where values outwith that range are eliminated. To do this we must make A::m_data private, override the implicit assignment operators and provide a an accessor and mutator to act as a gatekeepers to the member data:

struct A {

A(const int=1);

A(const A&);

A& operator= (const int);

A& operator= (const A&);

A& set_data(const int=1);

int get_data() const;

private:

int m_data;

};

A::A(const int data=1):m_data(1) {

set_data(data);

}

A::A(const A& a):m_data(a.m_data) {}

A& A::operator= (const int rhs) {

return(set_data(rhs));

}

A& A::operator= (const A& rhs) {

m_data = rhs.m_data;

return(*this)

}

A& A::set_data(const int data=1) {

if( data>=1 && data<=100)

m_data = data;

return(*this);

}

int A::get_data() const {

return( m_data );

}

Now we can guarantee that A::m_data will always be in the range 1 to 100. Note that the default constructor now initialises A::m_data to 1 before calling the setter, and that the setter only mutates A::m_data if the data argument is in the acceptable range.

Finally, let's look at a derived class and how we can efficiently invoke specific constructors. We'll use the same definition of A as above, and derive a new object from A.

struct B : public A {

B(const int=1);

B(const B&);

B& operator= (const B&)

};

B::B(const int data=1) : A(data) {}

B::B(const B& b) : A(b) {}

B& B::operator= (const B& rhs) {

A::operator= (rhs);

return(*this);

}

B& B::operator= (const int rhs) {

A::operator= (rhs);

return(*this);

}

Now it should be clear why we use construction syntax in the initialisation sections: it makes it possible to invoke specific constructors. Remember that objects are constructed from the least-derived object to the most-derived object. Thus in order for an instance of B to exist, A must be constructed first. It therefore makes sense to ensure that A is constructed as efficiently as possible, before constructing B. Had we chosen not to explicitly invoke A's default constructor, it would have been called implicitly instead -- but A::m_data would have been initialised to 1. This would then force us to initialise A::m_data to the correct value from within B's constructor body. This is far less efficient because A would have to be constructed first, followed by B, and then finally A::m_data could be initialised. By initialising through construction, A::m_data is fully initialised before B is constructed.

Although it may not always be possible to initialise all members through the constructor's initialisation section, you should always try and do as much initialisation as you possibly can through the initialisation section. It is also good practice to be explicit with your initialisation rather than rely on the implicit initialisation provided by your compiler, as this makes your intentions clear to the reader and, more importantly, to yourself.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: What is Constructor in C plus plus?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Related questions

Can you write own constructor in c plus plus?

Yes.


True or False A C plus plus class constructor cannot return a function value?

True - A C++ constructor cannot return a value.


What is the difference between implicit and explicit call of constructor in c plus plus?

An implicit constructor call will always call the default constructor, whereas explicit constructor calls allow to chose the best constructor and passing of arguments into the constructor.


Can constructor be declared as constant in c plus plus?

No. Constructors initialise objects and, by definition, must be able to modify the member variables. Uninitialised members are a disaster waiting to happen even without a constructor declared const! Thankfully, the compiler won't permit a const constructor.


What is the difference between constructor and friend function in c plus plus?

A constructor is a method that fires when the object is instantiated. A friend function is a function that has special access to the object. They are two different types of things, and cannot be further differenced.


How can a constructor be invoked at the time of inheritance in C Plus Plus?

It cannot. Inheritance is a compile-time operation. Constructors are invoked at runtime at the point of instantiation.


How do you invoke the constructor function in c plus plus?

There is no such thing as a constructor function in C++ (constructors have no return value, not even void, and cannot be called like regular functions). Constructors are invoked rather than called directly, either by declaring a static variable of the class type, or via the C++ new operator.


Constructor and destructor invocation in c?

Not possible in C.


What do you mean by initialisation of objects in c plus plus?

Initialization of objects means to provide an initial value for the object. This is usually done by the constructor, or it can be done with an assignment statement.


What is conustrutor?

A constructor is a function in C which has the same name of the class. The constructor can be used to initialize some function.


Write a program in c plus plus with constructor?

// constructor program to add two number's // program written by SuNiL kUmAr #include&lt;iostream.h&gt; #include&lt;conio.h&gt; class constructor { private: int a,b; public: constructor(int m,int n); int sum(); }; constructor::constructor(int m,int n) { a=m; b=n; } int constructor::sum() { int s; s=a+b; return (s); } int main() { int x,y; clrscr(); cout&lt;&lt;"enter two number's to add \n"; cin&gt;&gt;x&gt;&gt;y; class constructor k (x,y); cout&lt;&lt;"sum of two number's is = "&lt;&lt;k.sum(); getch(); return (0); }


Is Constructor Can be Private and Protective in c?

question i understand not