110 likes | 133 Views
Learn about classes, templates, and the key concepts of OOP in C++. Understand the attributes, behaviors, encapsulation, inheritance, and polymorphism of classes. Discover how to identify classes and design effective programs. Explore memory allocation and the constructor and destructor methods in C++.
E N D
CSCI 171 Presentation 15 Introduction to Object–Oriented Programming (OOP) in C++
Classes • Templates from which programmatic building blocks are constructed • Extension of structures • Model physical entities • Programmer can ‘construct’ instances of the templates • Instantiation • Class contains: • Attributes (variables) • Behaviors (methods)
Example • Write up the attributes and behaviors of a Car class
Objects • Actual instance of a class • In an object-oriented program objects interact with each other • Objects may be constructed from other objects • Black box concept • Other objects don’t care how an object performs its tasks, only that it does perform them
Important OOP concepts • Encapsulation • The instances of each class have complete control over the accessibility of their attributes and behaviors as defined by the class • Methods and variables act as a cohesive unit • Inheritance • Classes can be related in a hierarchical fashion from general to specific • Polymorphism • Some instances of classes have the ability to morph themselves into other (related) classes
Encapsulation • Access specifiers • public, protected, private • Generally speaking • methods are public • variables are private
Inheritance • Defining classes from general to specific • Allows for code reuse • Classes lower in a hierarchy obtain all features of higher level classes • All features should be put as high in the hierarchy as possible • Create a class hierarchy for all vehicle objects
Polymorphism • Assume we have a hierarchy with Animal at the top, and Crocodile and Dog below • An instance of an animal can reference a Crocodile at one time, and a Dog at another • This instance may respond differently to different methods depending on what it is referencing
Identifying Classes • Done in design phase • define, design, code, test, document • Most difficult part of OOP • must view entire system in OO terms • good initial design leads to highly effective programming • bad initial design leads to wasted time and effort
OOP in C++ • Classes consist of 2 parts • Header • all data and method signatures, and all corresponding access specification • Body • method bodies
OOP in C++ • Memory allocation – creating instances • Constructor method • Same name as class • If a pointer is used – dynamic memory allocation is done automatically using the keyword ‘new’ • If non-pointer – static memory allocation is done • Destructor method • Same name as class preceded by ~ • If a pointer is used –memory is freed using the keyword ‘delete’ • If non-pointer – destructor must be called explicitly