Class

Class

Class is data and functionality on that data wrapped into one. Class is a user-defined type. Class is a type. Object is an instance of a class. Example of an empty class:

#include <iostream>
class MyClass{

}; // class

int main(){
	MyClass myObject; // object of type MyClass
}

Data members

Class can have data members. We define two data members x and c, instantiate a class using a myObject and access the data members value using the .operator. The public: is an access-specifier that defines the visibility of members.

#include <iostream>
class MyClass{
public: // access-specifier
	int x; // data member 
	char c;
}; // class

int main(){
	MyClass myObject; // object
	myObject.x = 123; // accessing data member 
	myObject.c = 'A';
}

Member functions

Classes can have member functions. We define a simple printData() member function that will print out the value of class data members x and c. We access the member function through a myObject object followed by .operator followed by a call toprintData() member function:

#include <iostream>
class MyClass{
public:
	int x;
	char c;
	void printData(){ // member function
		std::cout << x < " " << c << std::endl;
};

int main(){
	MyClass myObject;
	myObject.x = 123;
	myObject.c = 'A';
	myObject.printData(); // call to a member function
}

Get and set values

Member functions can get or set data members values. Member function getValue() gets (returns) the data member value, the setValue(int value) function sets the data member value:

#include <iostream>
class MyClass{
public:
	int x;
	int getValue(){ // get value
		return x;
	}
	void setValue(int value){ // set value
		x = value;
	}
};

int main(){
	MyClass myObject;
	myObject.setValue(123); // sets the value of x
	int z = myObject.getValue(); // reads the value of x
	std::cout << "The value is: " << z << std::endl;
}