Help With Accessors & Classes, Coming from Struct.

I started programming in C++ again after many years away. I am having trouble understanding Classes. I understand struct and such, but really confused as to how classes work. I have read two different books on the subject and various tuts online but they all seem to have some odd way of explaining it where it just isn't clicking for me. In an effort to experiment, I have written this code and wondering if it's logical, correct and how would I pass data entered from cin, to pass back to the class MyCar. Anyone willing to take the time to properly rewrite it for correctabilty, I would be indebted to you greatly!

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

class Car
{
private:
	char Make[255];
	char Model[255];
	int Year_Made;
	int EngineCyl;
	int Doors;
	char TransmissonType[2];
	char DriveTrain[4];

public:
	void aMake();
	void aModel(char Model);
	int  aYearMade(int Year_Made);
	int  aCyl(int EngineCyl);
	int  aDoors(int Doors);
	void aTransmissionType(char TransmissonType);
	void aDriveTrain(char DriveTrain);
};

int main()
{
	Car MyCar;
	int iYear;
	cout << "What is the Year of Your Vehicle: ";
	cin >> iYear;
	
/* How to I report back the inputted year to the Accessor, to allow it to modify the Private Section? Or is there a better way or am I just trying something really stupid? I have a feeling in my gut it sounds like a pointer would do justice, but not sure how or if that needs to be implemented.
*/

	


	return 0;
}
Last edited on
In C++, the struct and class keywords mean the same thing, the only difference is the default privacy setting. There is very little "magic" with classes in C++. The big distinction comes from the way you design and use the class - the concepts of encapsulation and data hiding can be difficult to learn.

Generally in C++, you should only create an object when you have all the parts you need to make it. In your case, you should wait until after getting user input before you even think about your class. Also, most if not all of the information should be transferred via the class constructor - it's a bad idea to let an object exist in a partial or unconstructed state.

It would help to understand RAII, as this is a central part of understanding all classes and data structures in C++.

Also, you should be using std::string objects instead of C-style character arrays.
http://www.cplusplus.com/reference/string/string/
http://en.cppreference.com/w/cpp/string/basic_string
Last edited on
Topic archived. No new replies allowed.