Constructor and Attributes
One of the primary usage of the constructors is to initialize attributes of the class. A default constructor, for example, can be used to set initial values. For example:
main
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
class Person {
public:
Person() {
name = "undefined";
}
std::string name;
};
int main()
{
Person person;
std::cout << person.name;
}
12345678910111213141516#include <iostream> class Person { public: Person() { name = "undefined"; } std::string name; }; int main() { Person person; std::cout << person.name; }
If you don't specify value for name attribute of the object, it will be set to underfined as a default. You can try removing this constructor to see what changes occur.
Initializing Attributes with Constructor
Just as functions a constructor can accept parameters, allowing you to pass different arguments when instantiating an object. Also, constructor can be overrided, so you can increase flexibility, for instance varying number of arguments.
main
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Person {
public:
Person(std::string _name, std::string _surname, int _age)
{
name = _name;
surname = _surname;
age = _age;
}
std::string name;
std::string surname;
int age;
};
int main() { Person person("Bob", "Song", 23); }
123456789101112131415class Person { public: Person(std::string _name, std::string _surname, int _age) { name = _name; surname = _surname; age = _age; } std::string name; std::string surname; int age; }; int main() { Person person("Bob", "Song", 23); }
Tehtävä
Swipe to start coding
- Create a constructor for the Location class that takes three parameters and initializes the instance variables with these values.
- Output initialized attributes of the object to the console.
Ratkaisu
solution
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
class Location {
public:
Location(std::string _name, float _x, float _y) {
name = _name;
x = _x;
y = _y;
}
std::string name;
float x, y;
};
int main()
{
Location city("Rome", 41.902782, 12.496366);
std::cout << city.name << ' ' << city.x << ' ' << city.y;
}
Oliko kaikki selvää?
Kiitos palautteestasi!
Osio 2. Luku 2
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
class Location {
public:
___(___)
{
}
std::string name;
float x, y;
};
int main()
{
Location city("Rome", 41.902782, 12.496366);
std::cout << city.name << ' ' << city.x << ' ' << city.y;
}
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme