100 likes | 204 Views
This chapter provides an overview of object-oriented programming (OOP) in C++, focusing on critical concepts such as abstract data types, encapsulation, inheritance, pointers, and polymorphism. It explains the importance of defining program behavior, the relationship between data and operations, and how OOP allows for modeling real-world scenarios. The chapter covers how to create pointer variables, manage memory, and the principles of dynamic and static binding. Whether you're a beginner or looking to refresh your OOP knowledge, this chapter offers valuable insights into C++ programming.
E N D
Chapter 1 OO using C++
Abstract Data Types • Before we begin we should know how to accomplish the goal of the program • We should know all the input and output • The behavior of the program is important • We need to define how an item operates • An item specified in terms of operations is an Abstract Data Type
Encapsulation • Combining of data and related operations is called data encapsulation • An object is an instance of a class • In OO languages a connection between data and member functions at the outset • This allows for modeling fragments of the real world • It allows for easier error finding • We also can conceal details from other people
Inheritance • OOLs allow for creating a hierarchy of classes • The first class in the hierarchy is called the base class. • Other classes are called subclasses or derived classes
Pointers • Pointers are variables that contain the address of another variable • We can use the pointer variable to indirectly access the value being referenced by the pointer • Pointers and arrays are similar.
Pointers • To create a pointer variable we use the keyword new • When you want to free the memory we use the keyword delete • It is an error to try to use an address that is stored in a pointer after the delete command has been issued
Pointer vs. Array for ( sum = a[0], i = 1; i < 5; i++ ) sum += a[i]; for ( sum = *a, i = 1; i < 5; i++ ) sum += *(a + i); for ( sum = *a, p = a+1; p < a+5; p++ ) sum += *p;
Why does this work? • a + 1 denotes the next cell of the array. • a + 1 is equivalent to &a[1] • So if a = 1020, then a + 1 may not necessarily by 1021. The value will depend on the type stored in a and its sizeof value
Other pointer issues • When we are dealing with dynamic data, we have issues • Classes that contain dynamic data must always have a copy constructor • They also must have a destructor and an assignment operator • The class must take care of its data
Polymorphism • Polymorphism refers to how a function name can denote many functions that are members of different objects • This works because of the type of binding • Static binding is determined at compile time • Dynamic binding is determined at run time • In order to use dynamic binding, we need two conditions to be met: • Functions must be declared as virtual • A pointer to the object is used