Programming: Week 3

Week 3 is all about classes. Again, this is totally new to me but it is doable.

Just one exercise this time, more on classes to come.

Ex.2

Define a “Person” class. Within the class, define private variables (member variables/data members) to hold the age (an int) and the name (an std::string). Define public methods to assign values to the private variables and access the values in the private variables.

Use the class in a program so that the main() function calls the methods to manipulate the private variables.

#include 
#include 
#include 

class Person
{
	public:
	void setData(std::string nomen, int aetas)
		{
			name = nomen;
			age = aetas;
		};
	int getAge()
		{
			return age;
		};
	std::string getName()
		{
			return name;
		};
	int age; std::string name;
};

int main(int argc,char* argv[])
{
	std::string input_name;
	int input_age;
	Person p1;
	std::cout << "Please enter a person's name and age." << std::endl;
	std::cout <> input_name;
	std::cout <> input_age;
	p1.setData(input_name,input_age);
	std::cout << "Extracting data from the object ..." << std::endl;
	std::cout << "Name: " << p1.getName() << "tAge: " << p1.getAge() << std::endl;
	return 0;
}

In the version above, the main function reads the user input and passes it to the set method of the instantiated object p1. This method internally accesses the private variables name and age and assigns them the values input by the user.

Next, when we have to output the values the object p1 contains, we call the object’s get methods which again internally access the private data members and provide the values.

About Rokas Paulauskas

2014  Programming