Struct to Private Class?

So basically, last week our lab was to make a struct, public obviously. Now our instructor wants us to change it to a class. The problem is the the data has to be private. The Year, Make, Model, Miles, and Price are all supposed to be private. How do I gain access to them in the main() if they are private?

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
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

class car
{
	private:
		int year;
		string make;
		string model;
		float miles;
		float price;
	
	public:
		void converter(int a, string b, string c, float d, float e)
			{a=year; b=make; c=model; d=miles; e=price;}
};

int main(void converter())
{
	int a; string b; string c; float d; float e;
	const int number=2;
	car cars [number];
	int i;
	for(i=0; i<number; i++)
	{
		cout << "Enter the YEAR of the car: ";
		cin >> cars[i].a;
		cout << "Enter the MAKE of the car: ";
		cin >> cars[i].b;
		cout << "Enter the MODEL of the car: ";
		cin >> cars[i].c;
		cout << "Enter the number of MILES on the car: ";
		cin >> cars[i].d;
		cout << "Enter the PRICE of the car: ";
		cin >> cars[i].e;
		cout << " " << endl;
	}
 
	cout << "Cars listed: " << endl;
	for(i=0; i<number; i++)
	{
		cout << "Year: " << a << endl;
		cout << "Make: " << b << endl;
		cout << "Model: " << c << endl;
		cout << "Miles: " << d << endl;
		cout << "Price: $" << e << endl;
		cout << " " << endl;
		cout << "This is a " << a << " " << b << " " << c << " with " << d << " miles for $" << e << endl;
		cout << " " << endl;
	}
	system("pause");
};
Brandon23z wrote:
How do I gain access to them in the main() if they are private?
You're not supposed to. You should 'tell' the car class to print info about itself, rather than 'asking' about it and printing it yourself. Look up "Tell, Don't Ask".
I don't understand. I looked it up, but that looks way complicated for what we're doing. He said something about set and get.
How about a function that lets you set the info (setter or constructor) and a function that lets you ouput it?

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

class Test
{
    public:
        void input();
        void output();
    private:
        int info;
};


void Test::input()
{
    cout << "Please enter a number: " << endl;
    cin >> info;
}

void Test::output()
{
    cout << "The number entered was: " << info << endl;
}

int main()
{
    Test t1;

    t1.input();
    t1.output();

}
Giblit is right about the output function (it is "Tell, Don't Ask"), but I disagree with the input function (delayed construction is never good).
Topic archived. No new replies allowed.