Constructors help


Hello, I'm learning on how to use Constructors and I can't figure out what's the problem in the code below Can someone lend me a hand in fixing the code below and explain to me what's wrong in this code below. Thanks.

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
#include <iostream>


using namespace std;

 class Cars
    {
       public:
       string brand;
       string model;
       int price;
       
       Cars (string b, string m, int p)
       {
           brand = b;
           model = m;
           price = p;
       }
    };

int main()
{
   
   Cars a1 ("Nissan", "GTR-34", 24000 )
    
   cout << a1.brand << endl;
   cout << a1.model << endl;
   cout << a1.price << endl;
   

   Cars a2 ("Toyota", "Corolla AE 86", 1200000 )
   cout << a2.brand << endl;
   cout << a2.model << endl;
   cout << a2.price << endl;
    
    
    
    

    return 0;
} 






Only issues with that code is that line 24 and 31 don't end in semicolons.
A class with all members public is effectively a struct. #include <string> is missing. There's also a better way to initialise variables in a constructor. strings should be passed by const ref (or use move from a copy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>

struct Cars {
	std::string brand;
	std::string model;
	int price {};

	Cars(const std::string& b, const std::string& m, int p) : brand(b), model(m), price(p) {}
};

int main() {
	Cars a1("Nissan", "GTR-34", 24000);

	std::cout << '\n' << a1.brand << '\n';
	std::cout << a1.model << '\n';
	std::cout << a1.price << '\n';

	Cars a2("Toyota", "Corolla AE 86", 1200000);

	std::cout << '\n' << a2.brand << '\n';
	std::cout << a2.model << '\n';
	std::cout << a2.price << '\n';
}

1.You forget to include the head file---<string>, include it.
2.You forget to add ';' in the line 24 and 31, add it.
Last edited on
Topic archived. No new replies allowed.