Object Oriented Programming Lab Manual (Lab 02) : Topic: Shifting From Structural To Object Oriented Paradigm
Object Oriented Programming Lab Manual (Lab 02) : Topic: Shifting From Structural To Object Oriented Paradigm
1
Objectives:
The purpose of this activity is to get you familiar with the object oriented programming syntax in C++., importance of classes
on structs and their implementation. Learn the concept of data hiding and data encapsulation by using getter setter for data
member/variables in class.
Sample Code:
main.cpp
#include <iostream>
using namespace std;
struct item
int keep_data;
};
int main()
John_cat.keep_data = 10;
Joe_cat.keep_data = 11;
Big_cat.keep_data = 12;
"<<garfield<<"\n";
return 0;
2
Changing to Class
In C++ struct can only contain variables and we can't add functions in it. While in Classes we can add both variables and
functions
main.cpp
#include <iostream>
class item
public:
void set(int enter_value) // Also known as setter used to set user-defined values to private member variables.
It usually doesn’t have any return type.
{
keep_data = enter_value;
int get_value(void) //Also known as getter used to get private member variables values set by the setter.
It has a return type of the type of respective variable to be returned.
{
return keep_data;
}
private:
int keep_data;
};
int main()
item John_cat,Joe_cat,Big_cat;
John_cat.set(10);
Joe_cat.set(11);
Big_cat.set(12);
3
cout<<"\nAccessing data normally\n";
cout<<"---------------------------\n";
return 0;
#include<iostream>
using namespace std;
class rectangle
{
private:
int height;
int width;
public:
int area(void)
{
return (height * width);
}
void initialize(int initial_height, int initial_width)
{
height=initial_height;
width = initial_width;
}
};
int main()
{
rectangle wall;
wall.initialize(12,10);
return 0;
4
Lab Tasks
Note: All tasks must be code in single file.
Task 1:
Make a class of Car with parameter speed and function initialize_speed() and print_speed() and write test
program for it.
Task 2:
Make a class of Bike with parameters strokes, horsepower and function initialize() and print() and write test
program for it.
Task 3:
Make a class of School with parameters all int type: rooms, staff, students and function initialize() and print()
write test program for it.
Task 4:
Change task 1 and task 2 into user defined values (you are supposed to take input from user), use getter setters
for each variable to implement this task.