constructor vs setName()......

Here is my question...

1
2
3
4
5
6
7
8
9
class apple{
private:
string name;
Public:
apple(); 
apple(string a); // to set name=a;
void setName(string a){ //to set name=a also.
name=a;
};


1.) If you build a class, how many constructors can you have ? can i have two constructors like in the above codes ? one without and one with parameters?

2.) Does it make any difference if i set the name using the setName function or the constructor ? for example:

1
2
3
4
5
apple("peter");

and

apple.setName("peter");

Hey americanxo I am new to programming as well but I think I can help you with this . You can have as many constructors in a class as you want. The first constructor (parameter less) which you have declared is called the 'default constructor' and it holds a lot of importance. In case you donot define any constructor yourself the compiler will provide the default constructor but in case you have provided a constructor yourself than you have to provide it...you just can't go about there defining a Parameterised constructor without defining a Non parameterised default constructor , the system will give an error in this case.
2) No it doesnot make any difference. For eg. You can create a class object without passing any value and then you can set the name whichever you want using the Setname function.
Example:-
apple a;
a.setName("manav");

Goodluck!
thank you very much....
Topic archived. No new replies allowed.