doubt in objects creation

Can the objects in c++ created without using constructor?
For example in the following code
class value
{
int a;
public:
void getdata(int a)
{
cin>>a;
}
};
main()
{
value v;
v.getdata(1);
}
In the above code no constructor is defined.But the object 'v' is created.how?
If the object can be created without constructor then what is the use of constructor?please clear my doubts....

Last edited on
Every class has some sort of constructor, if it is not directly specified by the user then a default constructor is used to handle the memory in class objects (you don't see all of this happening, it is done behind the scenes)

A constructor is useful to pass values into the class when an object is first created, for example if you were creating a game you would want to pass the health/speed/etc into the constructor when the object is first created to make those the default values.
@James2250,
that means object v is created by the default constructor.compiler creates default constructor?
In this case, yep
@James2250,
Thank you
Constructor is used to initialize the objects, not to create the objects.
Why are you passing the variable by value in the function.

1
2
3
4
void getdata(int a)
{
        cin>>a;
}
¿Why is it passing a variable at all?
the compiler creates 3 things for a class if you don't provide them. I always forget these 3 and I would love it if someone could recall... It's something like:
1- default constructor
2 - assignment operator
3 - virtual destructor? [edit] copy constructor ? [/edit]
Last edited on
1) default constructor
2) assignment operator
3) copy constructor
4) destructor

Note that a default constructor is provided only if you do not define any of your own constructors.
while creation of objects, default constructor is automaticaly called.

value v;
or
value v = new value(); will do same work.........

here value() is default constructor

If anyone use only value v;
then this object will be initialized by other constructor
Last edited on
value v;
or
value v = new value(); will do same work.........

Uh, no? The second line will not compile. If you meant this:
value v = value();
then it will only match value v; if the compiler optimizes it. Otherwise you create a temporary value object and then use the copy constructor to create v.
value v = new value(); will do same work.........


If it is a no-arg constructor the syntax should be value *v = new value;
Topic archived. No new replies allowed.