Monday 28 December 2015

Basic OOP Program

 Object Oriented Programming or OOP is an approach to programming(in general) that is based on the view of treating each entity or element as an object, in such a way that each object is unaware of the existence of other objects. Before going further, let me lay out some basic details for you.

CLASS -  Many of you must have the definition of class as : "a class is the collection of data members of same or different type, grouped under a common name". Well this is actually a very trivial definition of class. A class serves as a blueprint for building something. Simply put, it is a layout that describes where everything should be put together. In programming
terminology, a class is a way of binding the data describing an entity and its associated functions together.

Now i can go on and on, about classes and object, why the use of classes, data abstraction and so on, but all that you can find in any textbook. Let us jump to the practical implementation of OOP.

The article follows a program that demonstrates the use of classes and objects. Before i get into the nitty gritty of it all, please understand that you need to focus on the concept , not the
technical details. The "TECH DETAILS" will come with time and practice. Focus must be on understanding the concept. So let's begin :

The following program creates a class "MarkSheet" with a single member variable "marks" of type int(a.k.a integer). Now the class also has two PUBLIC member functions, a setter function and a correspondinggetter function. Getter and Setter functions are not some SPECIAL functions, they are just named that way, sort of a trend. The job of a "getter" function is to return
the value of a variable of the class and the job of a "setter" function is to SET the value of a variable of the class.

For e.g : here is a demo setter function

void setDAY(int x) // sets the value of 'day' with the value contained by 'x'
{
     day = x;
}

Similarly, e.g : here is a demo getter function

int getDay() // 'gets' or returns the value of the variable 'day'
{
     return day;
}

The class has the following setter and getter functions :
1 - setMarks() // sets the marks of the student
2 - getMarks() // gets or returns the marks of the student

In the main() function, two objects,name objA and objB are declared that represent object of student A and B respectively. The program then prompts the user to enter the values
of the marks of students A and B. The marks are set by using the setMarks() setter function. After that, the marks are displayed by calling the getMarks() getter function.

No comments:

Post a Comment