Discuss C++ constructors in the C Programming forum on Dev Shed. C++ constructors C programming forum discussing all C derivatives, including C#, C++, Object-C, and even plain old vanilla C. These languages are low level languages, and used on projects such as device drivers, compilers, and even whole computer operating systems.
Posts: 66
Time spent in forums: 14 h 4 m
Reputation Power: 0
C++ constructors
just a bit confused about constructors concept....
see my example code here :
Code:
#include<iostream>
#include<stdio.h>
#include<conio.h>
using namespace std;
class integer
{
private:
int i;
public:
void getdata()
{
cout<<endl<<"Enter an integer";
cin>>i;
}
void setdata(int j)
{
i=j;
}
integer(){ //zero argument constructor
}
integer(int j) //one argument constructor
{
i=j;
}
void displaydata()
{
cout<<endl<<"value of i is : "<<i<<endl;
}
}
void main()
{
integer i1(100),i2,i3;
i1.displaydata();
i2.setdata(200);
i2.displaydata();
i3.getdata();
i3.displaydata();
getch();
}
Here i1(100) is one argument constructor.... if what i say is correct .. then i2 and i3 are zero argument constructors...
Does this imply that.. All class objects are by default zero arguments constructors? If all this is true then every object of class is always calling a constructor or it is a constructor.....
Posts: 6,123
Time spent in forums: 2 Months 2 Weeks 3 Days 16 h 5 m 8 sec
Reputation Power: 1949
Objects are not constructors. Rather, objects have constructors. They just have the name of the class. And the syntax of instantiating an object through declaration is to attach the arguments to the object name. How many and what datatypes of the arguments determine which constructor is used (as per the rules of function overloading). The default constructor is the one with no arguments.
Posts: 4,806
Time spent in forums: 1 Month 2 Days 17 h 19 m 38 sec
Reputation Power: 1800
When an object is created or comes into scope its constructor is automatically called. Which constructor is called is governed by the rules of function overloading - the constructor whose argument count and types match is called.
A constructor with no arguments is known as a default constructor - the one that is called when an object is instantiated with no arguments.
Posts: 4,806
Time spent in forums: 1 Month 2 Days 17 h 19 m 38 sec
Reputation Power: 1800
Quote:
Originally Posted by remunance
Why important constructor in program
The ability to automatically (and correctly) initialise an object reduces the scope for errors - the designer of the class can ensure that it is performed to their design rather than relying on the user of the class to have to know how to do that, and more importantly to avoid having to give the user the means to do that (correctly or otherwise).
That is to say it minimises the ways in which an object can be use incorrectly.