Object Oriented Programming: Lecture Notes 02
Author: A. El-Gadi/Faculty of Computer Engineering/Tripoli University
Author: A. El-Gadi/Faculty of Computer Engineering/Tripoli University
C-style structs come close to achieving one of the central pillars of object oriented programming called encapsulation. Encapsulation in its fullest sense is the principle of encapsulating all attributes and behavior of some type as an integral part of the type. To achieve encapsulation in the fullest sense of the term, we need more than C-style structs for reasons that will become clear later. In the terminology of OOP this concept is called class. Classes are used to define and describe kinds of things (tables, bottles, cars, human beings, mathematical equations, numbers and so on). Each class is a general statement about the kind it describes. In C++, the class syntax in its simplest can look like the following:
class Rectangle{public:
double height;
double width;
};
The class above is a class that defines a rectangle. The keyword public is used to make the attributes or member variable that come after it visible to the outside. Its importance will become clear later in the course.
The following example illustrates how to use our simple class:
class Rectangle{public:
double height;
double width;
};
#include<iostream>
int main(){Rectangle r1; double temp;
temp=r1.height+r1.width;
}
Notice how we could access the member variable of the class using the dot operator. The syntax, as you might have noticed, is akin to the struct syntax. Also note that the new type Rectangle is not preceded by the keyword class when defining objects of its type.
No comments:
Post a Comment