Question about how to interpret constructors

Jun 23, 2018 at 11:02am
So I have a question about the constructor(s) in a class. Reason why I put constructors in plural here is also apart of the question.

Because, is a "constructor" only for something that doesn't take any parameters? Say I have a class called Bob.

1
2
3
4
5
6
7
8
class Bob{
public:
     Bob();
     Bob(int a);
};


Would the constructor be [code]Bob()
here? Or would Bob(int a) also be a constructor? I am kinda confused about this.

Also, how would I refer to these two? Because these aren't functions, or are they?

Thanks in advance!
Last edited on Jun 23, 2018 at 11:03am
Jun 23, 2018 at 11:05am
Those are two different constructors. You would typically refer to them as "constructors"; that's the standard term. They are functions that get run when the object is created.

1
2
Bob someNewBobObject; // this would cause the constructor Bob() to be run
Bob anotherBobObject(7); // this would cause the constructor Bob(int a) to be run 

Last edited on Jun 23, 2018 at 11:06am
Jun 23, 2018 at 11:10am
hi,

Constructors are functions with the same name as the class. Like any other function overloading, they must differ in the types and number of arguments that is unique, including no arguments. That is how the compiler knows which one to call. So it is not so much referring to them, it's calling them.

Good Luck !!


Jun 23, 2018 at 7:04pm
In this example you would call Bob(); the default constructor. It is the constructor that gets used without any user supplied arguments. The Bob(int a); is also a constructor, but this time the user wants to supply the value for int a.

Example...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>

class Bob{
     int BobsInt;
public:

     Bob();
     Bob(int a);
     
     int getBobsInt();
};

Bob::Bob() {
 BobsInt = 5; //The default value   
}

Bob::Bob(int a) {
 BobsInt = a;//The user supplied value   
}

int Bob::getBobsInt() {
    return BobsInt;
}

int main() {
    Bob Bob1;//the default constructor called
    Bob Bob2(7);//constructor with user input
    
    std::cout << Bob1.getBobsInt();
    std::cout << "\t" << Bob2.getBobsInt();
    
   return 0;
}
Last edited on Jun 23, 2018 at 7:04pm
Topic archived. No new replies allowed.