C++: A class with only data members

As was explained in the previous post, a class would contain data members and methods.

For the purpose of explanation, let’s create a class with only data members.

#include <iostream>
#include <string>

using namespace std;

class Country
{

public:
	string name;
	int noAlbum;
	string latest;

};

int main()
{

	Country ts; // instance declaration

	ts.name = "Taylor Swift"; // member initialization
	ts.noAlbum = 5;
	ts.latest = "1986";

	cout << "\n Country Singer = " << ts.name;
	cout << "\n No of Album = " << ts.noAlbum;
	cout << "\n Her latest album = " << ts.latest;
	cout << "\n";

	return 0;
}

The class that we have created here is called Country.  There are 3 data members for this class.

To access the 3 members, we need to create an instance of the class and in our case, it is called ts.  You can actually create many instances of the Country class and call them ts1, ts2, ts3 etc.

To access the data, we use the dot operator and in this example, we use ts.name to access and initialize the name, which is a data member of the class.

datamembers

Series Navigation<< C++: Classes and objects
C++ Keywords >>