Object Oriented Programming is a programming technique in which programming is based in objects.

What is Object?

Object is any entity about which data is collected. Object may be a Fan, Person, Car etc.

What is Class?

Class is collection of objects having same properties and function.

For example if we have a object like Person then

Person have following properties:

  • Color
  • Name
  • Age
  • Height etc.

Similarly it has following functions:

  • Speaking
  • Weeping
  • Eating
  • Walking etc.

Syntax of class Person in C++

class Person

{
  private:
//class member variables definitions. public:
//class member functions definition }

You can practice other programming questions for C and C++ Exercises.

WE provided a large Variety of solved programming exercises.

Functions Programming Exercises 

Question Number 5

Write a class Car that contains the following attributes:

  • The name of car
  • The direction of car (E, W, N, S)
  • The position of car (from imaginary zero point)

The class has the following member functions:

  • A constructor to initialize the attributes.
  • Turn function to change the direction of car to one step right side (e.g. if the direction is to E, it it should be change to S and so on.)
  • Overload the Turn function to change the direction to any side directly. It should accept the direction as parameter.
  • Move function to change the position of car away from zero point. It should accept the distance as parameter.
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<string.h>
using namespace std;

class Car
{
	char name[50], dir;
	int pos;
	public:
		Car()
		{
			strcpy(name, "Noname");
			dir = 'E';
			pos = 0;
		}
		void reset()
		{
			cout<<"Enter car name: ";
			gets(name);
			cout<<"Enter direction: ";
			cin>>dir;
			cout<<"Enter position: ";
			cin>>pos;
		}
		void turn()
		{
			if(dir == 'E')
			dir = 'N';
			else if(dir == 'N')
			dir = 'W';
			else if(dir == 'W')
			dir = 'S';
			else if(dir == 'S')
			dir = 'E';
		}
		void turn(char d)
		{
			dir = d;
		}
		void move(int d)
		{
			pos = pos + d;
		}
		void show()
		{
			cout<<"The direction of car is ";
			switch(dir)
			{
				case 'E':
					cout<<"East";
					break;
				case 'N':
					cout<<"North";
					break;
				case 'W':
					cout<<"West";
					break;
				case 'S':
					cout<<"South";
					break;	
			}
			cout<<"\nIt is standing at "<<pos<<"position."<<endl;
		}
};
        main()
        {
	       Car x;
	       x.reset();
	       x.show();
	       x.turn();
	       x.move(100);
	       x.show();
        }

Leave a Reply