forked from portfoliocourses/cplusplus-example-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstructor_basics.cpp
More file actions
98 lines (77 loc) · 2.21 KB
/
constructor_basics.cpp
File metadata and controls
98 lines (77 loc) · 2.21 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*******************************************************************************
*
* Program: Constructor Basics
*
* Description: Demonstrates the basics of using constructor functions in C++.
*
* YouTube Lesson: https://www.youtube.com/watch?v=bnyveJ17lao
*
* Author: Kevin Browne @ https://portfoliocourses.com
*
*******************************************************************************/
#include <iostream>
using namespace std;
// object type for representing cats
class Cat
{
// cats will have a name, color and favorite toy
private:
string name;
string color;
string favorite_toy;
public:
// member function for printing out a cat's information
void print_cat()
{
cout << "Name: " << name << endl;
cout << "Color: " << color << endl;
cout << "Favourite Toy: " << favorite_toy << endl;
}
// constructor with no parameters, we initialize member variables to defaults
Cat()
{
name = "Unknown";
color = "Unknown";
favorite_toy = "Unknown";
}
// constructor with a single parameter, we use it to intitialize the cat name
Cat(string n)
{
name = n;
color = "Unknown";
favorite_toy = "Uknown";
}
// constructor parameters can have default values such as the default favorite
// toy value "Laser Pointer", we can also define constructors outside the
// Class such as this example, as long as we leave function declaration
// (i.e. prototype) in the class
Cat(string n, string c, string ft = "Laser Pointer");
};
// we use the syntax ClassName::ClassName( ... ) to define the constructor
// outside the class...
Cat::Cat(string n, string c, string ft)
{
name = n;
color = c;
favorite_toy = ft;
}
int main()
{
// the constructor with no parameters will be called
Cat cat1;
cout << "Cat 1..." << endl;
cat1.print_cat();
cout << endl;
// the constructor that accepts a single argument will be called
Cat cat2("Spot");
cout << "Cat 2..." << endl;
cat2.print_cat();
cout << endl;
// the constructor that accepts 3 arguments will be called, but the default
// value will be used for the 3rd argument
Cat cat3("Garfield", "Orange");
cout << "Cat 3..." << endl;
cat3.print_cat();
cout << endl;
return 0;
}