This code will generate a compile time error as Base is an abstract class due to pure virtual function show(). An abstract class cannot be instantiated.
The document discusses object oriented programming concepts in C++ like classes, objects, data members, member functions etc. It provides code examples to demonstrate defining classes with data members and member functions, creating objects of a class, accessing data members and calling member functions. It also shows the difference between declaring members as public or private. One example creates an Employee class with functions to get employee details like salary, working hours and calculate final salary. Another example creates an Employee class to store and print details of 3 employees like name, year of joining and address.
This document provides an overview of object-oriented programming (OOP) concepts in C++. It defines key OOP concepts like class, object, inheritance, encapsulation, abstraction, polymorphism, and overloading. It provides examples to illustrate class and object, inheritance with different types, encapsulation by hiding data, and function overloading. The document was prepared by a trainee as part of a mentoring program and provides contact information for the training organization.
Example for Abstract Class and Interface.pdfrajaratna4
This document discusses abstract classes and interfaces in C++. It provides three examples:
1) An abstract Shape class with pure virtual calculateArea() function is implemented by Square and Circle classes. This enforces that derived classes provide an implementation of calculateArea().
2) A Shape interface with pure virtual draw() function is implemented by Rectangle and Circle classes, each providing their own draw() method.
3) Another abstract Shape class with pure virtual getArea() function and width/height properties is implemented by Rectangle and Triangle classes, each providing their own getArea() calculation based on width and height.
Chapter 2 OOP using C++ (Introduction).pptxFiraolGadissa
Introduction to Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data, or objects, rather than functions and logic. It is widely used for developing complex, scalable, and maintainable software systems. The core principles of OOP include encapsulation, abstraction, inheritance, and polymorphism.
Key Concepts of OOP
Encapsulation: This involves bundling data and methods that operate on that data within a single unit, called an object. It helps protect the internal state of an object from external interference23.
Abstraction: This principle focuses on exposing only necessary information while hiding complex details. It allows users to interact with objects without knowing their internal workings23.
Inheritance: This feature enables a new class (subclass) to inherit properties and behaviors from an existing class (superclass), promoting code reuse and hierarchical organization23.
Polymorphism: This allows objects of different classes to be treated as objects of a common superclass. It enables multiple behaviors to be implemented through a common interface23.
Object Technology and Programming Environment
Object Technology: This refers to the use of objects to model real-world entities in software development. It includes classes, objects, inheritance, polymorphism, and encapsulation7.
Programming Environment: OOP is typically supported in class-based languages like Java, Python, and C++. These environments provide tools for designing, developing, and testing object-oriented software
This document provides an overview of object-oriented programming concepts in C++, including objects, classes, data abstraction, encapsulation, inheritance, and polymorphism. It defines each concept, provides examples in C++ code, and explains how they are implemented and relate to each other. The document is presented as part of a mentoring program to teach OOP concepts.
The document provides an introduction to object-oriented programming (OOP) concepts in C++ including objects, classes, abstraction, encapsulation, inheritance, polymorphism, constructors, destructors, and exception handling. It defines each concept and provides examples of how it is implemented in C++ code. For instance, it explains that a class is a user-defined data type that holds its own data members and member functions, and provides an example class declaration. It also discusses polymorphism and provides examples demonstrating method overloading and overriding.
Operator overloading allows programmers to define special member functions to customize the behavior of operators (like +, -, etc.) for user-defined types. It can be implemented through member functions, non-member functions, or friend functions. Inline functions replace function calls with the function code directly, which can improve performance for short functions.
The document discusses object oriented programming concepts like class, object, encapsulation, inheritance and polymorphism. It provides examples of defining a class with data members and member functions in C++. It also explains constructors, destructors, different types of constructors like default, parameterized and copy constructor. Examples are given to illustrate how objects are created from a class and how member functions can be defined internally or externally.
Operator overloading allows programmers to define special member functions to give class objects behaviors similar to built-in types when operators are used. There are three ways to implement operator overloading functions: member functions, non-member functions, and friend functions. Member functions are called as methods on the object while non-member functions are called independently. Friend functions have access to private members.
The document provides information about classes and objects in C++. Some key points:
- A class defines a user-defined data type by binding data and functions together. It contains data members and member functions.
- Classes have access specifiers like private, public, and protected that control access to members.
- Objects are instances of a class that allocate memory dynamically. They are used to access class members by using dot operator.
- Member functions can access private data members while non-member functions cannot. Memory is separately allocated for each object's data members.
- Static members have single copy shared among all objects rather than each object having its own copy. They are initialized only once.
The document discusses several key concepts in C++ classes including:
1. Friend classes allow one class to access the private members of another class.
2. Inline functions expand the function code in place rather than calling the function.
3. Parameterized constructors allow passing arguments to initialize object properties.
4. Static class members are shared across all objects rather than each object having its own copy.
In this short presentation struct inheritance and virtual member function in pure C are demonstrated. With these fundamental techniques, more advanced design patterns are unlocked.
This lab report discusses object-oriented programming concepts like classes, objects, inheritance, and constructors in Java. It includes:
1) A class defines common properties and behaviors for a group of objects, while an object is an instance of a class. A house is an object with state like address and behavior like opening doors.
2) A constructor initializes an object when it is created and can be overloaded with different parameters. Getter and setter methods are used to access private variables.
3) Inheritance allows a subclass to inherit properties and behaviors from a parent class in a hierarchical relationship. This lab report provides examples of single, multilevel, and hierarchical inheritance in Java code.
1) A base class pointer can point to a derived class object but cannot access the derived class's additional functions without a cast.
2) Declaring a function as virtual in the base class allows it to be overridden in derived classes and called polymorphically through a base class pointer.
3) A pure virtual function is like an abstract function that derived classes must implement. A class with a pure virtual function is an abstract class that cannot be instantiated.
The document provides an overview of object-oriented programming concepts in C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance and polymorphism. It also covers procedural programming in C++ and compares it with OOP. Examples are provided to demonstrate creating classes, objects, functions, constructors and destructors. The document contains information on basic C++ programming concepts needed to understand and implement OOP principles in C++ programs.
Inheritance, Polymorphism, and Virtual Functions allows code reuse through inheritance. It establishes a hierarchical relationship between classes where a derived class inherits attributes and behaviors from its base class. Constructors and destructors of base classes are automatically called when objects of derived classes are created or destroyed. Derived classes can pass arguments to base class constructors and multiple inheritance determines the order of constructor calls. Object composition allows classes to contain instances of other classes to reuse their functionality.
The document discusses 5 object-oriented programming techniques:
1) Avoid calling virtual functions from constructors due to polymorphism issues.
2) Preserve method properties like signatures when overriding to adhere to principles like Liskov substitution.
3) Be aware of initialization order problems between classes and languages.
4) Avoid switch/if-else chains checking types and instead use polymorphism with virtual functions.
5) Be cautious of name hiding between scopes as it reduces readability and can cause defects.
C# is similar to C++ but easier to use, as it does not support pointers, multiple inheritance, header files or global variables. Everything must live within a class or struct. The basic syntax will be familiar to C++ programmers. Key features include properties, interfaces, foreach loops, and delegates for event handling. Properties allow custom getter and setter logic and are preferred over public fields. Delegates provide a type-safe way to link methods, and events build on this to prevent issues with multicast delegates. Generics and assemblies are analogous to C++ templates and deployment units.
SVD is a powerful matrix factorization technique used in machine learning, data science, and AI. It helps with dimensionality reduction, image compression, noise filtering, and more.
Mastering SVD can give you an edge in handling complex data efficiently!
More Related Content
Similar to Object Oriented Programming (OOP) using C++ - Lecture 4 (20)
Example for Abstract Class and Interface.pdfrajaratna4
This document discusses abstract classes and interfaces in C++. It provides three examples:
1) An abstract Shape class with pure virtual calculateArea() function is implemented by Square and Circle classes. This enforces that derived classes provide an implementation of calculateArea().
2) A Shape interface with pure virtual draw() function is implemented by Rectangle and Circle classes, each providing their own draw() method.
3) Another abstract Shape class with pure virtual getArea() function and width/height properties is implemented by Rectangle and Triangle classes, each providing their own getArea() calculation based on width and height.
Chapter 2 OOP using C++ (Introduction).pptxFiraolGadissa
Introduction to Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data, or objects, rather than functions and logic. It is widely used for developing complex, scalable, and maintainable software systems. The core principles of OOP include encapsulation, abstraction, inheritance, and polymorphism.
Key Concepts of OOP
Encapsulation: This involves bundling data and methods that operate on that data within a single unit, called an object. It helps protect the internal state of an object from external interference23.
Abstraction: This principle focuses on exposing only necessary information while hiding complex details. It allows users to interact with objects without knowing their internal workings23.
Inheritance: This feature enables a new class (subclass) to inherit properties and behaviors from an existing class (superclass), promoting code reuse and hierarchical organization23.
Polymorphism: This allows objects of different classes to be treated as objects of a common superclass. It enables multiple behaviors to be implemented through a common interface23.
Object Technology and Programming Environment
Object Technology: This refers to the use of objects to model real-world entities in software development. It includes classes, objects, inheritance, polymorphism, and encapsulation7.
Programming Environment: OOP is typically supported in class-based languages like Java, Python, and C++. These environments provide tools for designing, developing, and testing object-oriented software
This document provides an overview of object-oriented programming concepts in C++, including objects, classes, data abstraction, encapsulation, inheritance, and polymorphism. It defines each concept, provides examples in C++ code, and explains how they are implemented and relate to each other. The document is presented as part of a mentoring program to teach OOP concepts.
The document provides an introduction to object-oriented programming (OOP) concepts in C++ including objects, classes, abstraction, encapsulation, inheritance, polymorphism, constructors, destructors, and exception handling. It defines each concept and provides examples of how it is implemented in C++ code. For instance, it explains that a class is a user-defined data type that holds its own data members and member functions, and provides an example class declaration. It also discusses polymorphism and provides examples demonstrating method overloading and overriding.
Operator overloading allows programmers to define special member functions to customize the behavior of operators (like +, -, etc.) for user-defined types. It can be implemented through member functions, non-member functions, or friend functions. Inline functions replace function calls with the function code directly, which can improve performance for short functions.
The document discusses object oriented programming concepts like class, object, encapsulation, inheritance and polymorphism. It provides examples of defining a class with data members and member functions in C++. It also explains constructors, destructors, different types of constructors like default, parameterized and copy constructor. Examples are given to illustrate how objects are created from a class and how member functions can be defined internally or externally.
Operator overloading allows programmers to define special member functions to give class objects behaviors similar to built-in types when operators are used. There are three ways to implement operator overloading functions: member functions, non-member functions, and friend functions. Member functions are called as methods on the object while non-member functions are called independently. Friend functions have access to private members.
The document provides information about classes and objects in C++. Some key points:
- A class defines a user-defined data type by binding data and functions together. It contains data members and member functions.
- Classes have access specifiers like private, public, and protected that control access to members.
- Objects are instances of a class that allocate memory dynamically. They are used to access class members by using dot operator.
- Member functions can access private data members while non-member functions cannot. Memory is separately allocated for each object's data members.
- Static members have single copy shared among all objects rather than each object having its own copy. They are initialized only once.
The document discusses several key concepts in C++ classes including:
1. Friend classes allow one class to access the private members of another class.
2. Inline functions expand the function code in place rather than calling the function.
3. Parameterized constructors allow passing arguments to initialize object properties.
4. Static class members are shared across all objects rather than each object having its own copy.
In this short presentation struct inheritance and virtual member function in pure C are demonstrated. With these fundamental techniques, more advanced design patterns are unlocked.
This lab report discusses object-oriented programming concepts like classes, objects, inheritance, and constructors in Java. It includes:
1) A class defines common properties and behaviors for a group of objects, while an object is an instance of a class. A house is an object with state like address and behavior like opening doors.
2) A constructor initializes an object when it is created and can be overloaded with different parameters. Getter and setter methods are used to access private variables.
3) Inheritance allows a subclass to inherit properties and behaviors from a parent class in a hierarchical relationship. This lab report provides examples of single, multilevel, and hierarchical inheritance in Java code.
1) A base class pointer can point to a derived class object but cannot access the derived class's additional functions without a cast.
2) Declaring a function as virtual in the base class allows it to be overridden in derived classes and called polymorphically through a base class pointer.
3) A pure virtual function is like an abstract function that derived classes must implement. A class with a pure virtual function is an abstract class that cannot be instantiated.
The document provides an overview of object-oriented programming concepts in C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance and polymorphism. It also covers procedural programming in C++ and compares it with OOP. Examples are provided to demonstrate creating classes, objects, functions, constructors and destructors. The document contains information on basic C++ programming concepts needed to understand and implement OOP principles in C++ programs.
Inheritance, Polymorphism, and Virtual Functions allows code reuse through inheritance. It establishes a hierarchical relationship between classes where a derived class inherits attributes and behaviors from its base class. Constructors and destructors of base classes are automatically called when objects of derived classes are created or destroyed. Derived classes can pass arguments to base class constructors and multiple inheritance determines the order of constructor calls. Object composition allows classes to contain instances of other classes to reuse their functionality.
The document discusses 5 object-oriented programming techniques:
1) Avoid calling virtual functions from constructors due to polymorphism issues.
2) Preserve method properties like signatures when overriding to adhere to principles like Liskov substitution.
3) Be aware of initialization order problems between classes and languages.
4) Avoid switch/if-else chains checking types and instead use polymorphism with virtual functions.
5) Be cautious of name hiding between scopes as it reduces readability and can cause defects.
C# is similar to C++ but easier to use, as it does not support pointers, multiple inheritance, header files or global variables. Everything must live within a class or struct. The basic syntax will be familiar to C++ programmers. Key features include properties, interfaces, foreach loops, and delegates for event handling. Properties allow custom getter and setter logic and are preferred over public fields. Delegates provide a type-safe way to link methods, and events build on this to prevent issues with multicast delegates. Generics and assemblies are analogous to C++ templates and deployment units.
SVD is a powerful matrix factorization technique used in machine learning, data science, and AI. It helps with dimensionality reduction, image compression, noise filtering, and more.
Mastering SVD can give you an edge in handling complex data efficiently!
Have you upgraded your application from Qt 5 to Qt 6? If so, your QML modules might still be stuck in the old Qt 5 style—technically compatible, but far from optimal. Qt 6 introduces a modernized approach to QML modules that offers better integration with CMake, enhanced maintainability, and significant productivity gains.
In this webinar, we’ll walk you through the benefits of adopting Qt 6 style QML modules and show you how to make the transition. You'll learn how to leverage the new module system to reduce boilerplate, simplify builds, and modernize your application architecture. Whether you're planning a full migration or just exploring what's new, this session will help you get the most out of your move to Qt 6.
Key AI Technologies Used by Indian Artificial Intelligence CompaniesMypcot Infotech
Indian tech firms are rapidly adopting advanced tools like machine learning, natural language processing, and computer vision to drive innovation. These key AI technologies enable smarter automation, data analysis, and decision-making. Leading developments are shaping the future of digital transformation among top artificial intelligence companies in India.
For more information please visit here https://www.mypcot.com/artificial-intelligence
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...Natan Silnitsky
In a world where speed, resilience, and fault tolerance define success, Wix leverages Kafka to power asynchronous programming across 4,000 microservices. This talk explores four key patterns that boost developer velocity while solving common challenges with scalable, efficient, and reliable solutions:
1. Integration Events: Shift from synchronous calls to pre-fetching to reduce query latency and improve user experience.
2. Task Queue: Offload non-critical tasks like notifications to streamline request flows.
3. Task Scheduler: Enable precise, fault-tolerant delayed or recurring workflows with robust scheduling.
4. Iterator for Long-running Jobs: Process extensive workloads via chunked execution, optimizing scalability and resilience.
For each pattern, we’ll discuss benefits, challenges, and how we mitigate drawbacks to create practical solutions
This session offers actionable insights for developers and architects tackling distributed systems, helping refine microservices and adopting Kafka-driven async excellence.
Integrating Survey123 and R&H Data Using FMESafe Software
West Virginia Department of Transportation (WVDOT) actively engages in several field data collection initiatives using Collector and Survey 123. A critical component for effective asset management and enhanced analytical capabilities is the integration of Geographic Information System (GIS) data with Linear Referencing System (LRS) data. Currently, RouteID and Measures are not captured in Survey 123. However, we can bridge this gap through FME Flow automation. When a survey is submitted through Survey 123 for ArcGIS Portal (10.8.1), it triggers FME Flow automation. This process uses a customized workbench that interacts with a modified version of Esri's Geometry to Measure API. The result is a JSON response that includes RouteID and Measures, which are then applied to the feature service record.
In today's world, artificial intelligence (AI) is transforming the way we learn.
This talk will explore how we can use AI tools to enhance our learning experiences, by looking at some (recent) research that has been done on the matter.
But as we embrace these new technologies, we must also ask ourselves:
Are we becoming less capable of thinking for ourselves?
Do these tools make us smarter, or do they risk dulling our critical thinking skills?
This talk will encourage us to think critically about the role of AI in our education. Together, we will discover how to use AI to support our learning journey while still developing our ability to think critically.
Plooma is a writing platform to plan, write, and shape books your wayPlooma
Plooma is your all in one writing companion, designed to support authors at every twist and turn of the book creation journey. Whether you're sketching out your story's blueprint, breathing life into characters, or crafting chapters, Plooma provides a seamless space to organize all your ideas and materials without the overwhelm. Its intuitive interface makes building rich narratives and immersive worlds feel effortless.
Packed with powerful story and character organization tools, Plooma lets you track character development and manage world building details with ease. When it’s time to write, the distraction-free mode offers a clean, minimal environment to help you dive deep and write consistently. Plus, built-in editing tools catch grammar slips and style quirks in real-time, polishing your story so you don’t have to juggle multiple apps.
What really sets Plooma apart is its smart AI assistant - analyzing chapters for continuity, helping you generate character portraits, and flagging inconsistencies to keep your story tight and cohesive. This clever support saves you time and builds confidence, especially during those complex, detail packed projects.
Getting started is simple: outline your story’s structure and key characters with Plooma’s user-friendly planning tools, then write your chapters in the focused editor, using analytics to shape your words. Throughout your journey, Plooma’s AI offers helpful feedback and suggestions, guiding you toward a polished, well-crafted book ready to share with the world.
With Plooma by your side, you get a powerful toolkit that simplifies the creative process, boosts your productivity, and elevates your writing - making the path from idea to finished book smoother, more fun, and totally doable.
Get Started here: https://www.plooma.ink/
Providing Better Biodiversity Through Better DataSafe Software
This session explores how FME is transforming data workflows at Ireland’s National Biodiversity Data Centre (NBDC) by eliminating manual data manipulation, incorporating machine learning, and enhancing overall efficiency. Attendees will gain insight into how NBDC is using FME to document and understand internal processes, make decision-making fully transparent, and shine a light on underlying code to improve clarity and reduce silent failures.
The presentation will also outline NBDC’s future plans for FME, including empowering staff to access and query data independently, without relying on external consultants. It will also showcase ambitions to connect to new data sources, unlock the full potential of its valuable datasets, create living atlases, and place its valuable data directly into the hands of decision-makers across Ireland—ensuring that biodiversity is not only protected but actively enhanced.
Marketo & Dynamics can be Most Excellent to Each Other – The SequelBradBedford3
So you’ve built trust in your Marketo Engage-Dynamics integration—excellent. But now what?
This sequel picks up where our last adventure left off, offering a step-by-step guide to move from stable sync to strategic power moves. We’ll share real-world project examples that empower sales and marketing to work smarter and stay aligned.
If you’re ready to go beyond the basics and do truly most excellent stuff, this session is your guide.
AI and Deep Learning with NVIDIA TechnologiesSandeepKS52
Artificial intelligence and deep learning are transforming various fields by enabling machines to learn from data and make decisions. Understanding how to prepare data effectively is crucial, as it lays the foundation for training models that can recognize patterns and improve over time. Once models are trained, the focus shifts to deployment, where these intelligent systems are integrated into real-world applications, allowing them to perform tasks and provide insights based on new information. This exploration of AI encompasses the entire process from initial concepts to practical implementation, highlighting the importance of each stage in creating effective and reliable AI solutions.
In this session we cover the benefits of a migration to Cosmos DB, migration paths, common pain points and best practices. We share our firsthand experiences and customer stories. Adiom is the trusted partner for migration solutions that enable seamless online database migrations from MongoDB to Cosmos DB vCore, and DynamoDB to Cosmos DB for NoSQL.
In a tight labor market and tighter economy, PMOs and resource managers must ensure that every team member is focused on the highest-value work. This session explores how AI reshapes resource planning and empowers organizations to forecast capacity, prevent burnout, and balance workloads more effectively, even with shrinking teams.
Top 5 Task Management Software to Boost Productivity in 2025Orangescrum
In this blog, you’ll find a curated list of five powerful task management tools to watch in 2025. Each one is designed to help teams stay organized, improve collaboration, and consistently hit deadlines. We’ve included real-world use cases, key features, and data-driven insights to help you choose what fits your team best.
Wondershare PDFelement Pro 11.4.20.3548 Crack Free DownloadPuppy jhon
➡ 🌍📱👉COPY & PASTE LINK👉👉👉 ➤ ➤➤ https://drfiles.net/
Wondershare PDFelement Professional is professional software that can edit PDF files. This digital tool can manipulate elements in PDF documents.
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesMarjukka Niinioja
Teams delivering API are challenges with:
- Connecting APIs to business strategy
- Measuring API success (audit & lifecycle metrics)
- Partner/Ecosystem onboarding
- Consistent documentation, security, and publishing
🧠 The big takeaway?
Many teams can build APIs. But few connect them to value, visibility, and long-term improvement.
That’s why the APIOps Cycles method helps teams:
📍 Start where the pain is (one “metro station” at a time)
📈 Scale success across strategy, platform, and operations
🛠 Use collaborative canvases to get buy-in and visibility
Want to try it and learn more?
- Follow APIOps Cycles in LinkedIn
- Visit the www.apiopscycles.com site
- Subscribe to email list
-
Revolutionize Your Insurance Workflow with Claims Management SoftwareInsurance Tech Services
Claims management software enhances efficiency, accuracy, and satisfaction by automating processes, reducing errors, and speeding up transparent claims handling—building trust and cutting costs. Explore More - https://www.damcogroup.com/insurance/claims-management-software
4. #include <iostream>
#include <cstring> //for strcpy(), etc
using namespace std;
class String
{
private:
char *str; //pointer to string
public:
String(char *s) //constructor, one arg
{
int length = strlen(s); //length of string argument
str = new char[length + 1]; //get memory
strcpy(str, s); //copy argument to it
}
~String() //destructor
{
cout << "Deleting str.n";
delete[] str; //release memory
}
void display() //display the String
{
cout << str << endl;
}
};
int main()
{
String s1 = "Who knows nothing doubts nothing.";
cout << "s1 = "; //display string
s1.display();
return 0;
}
A String class using
new and delete
5. #include <iostream>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
void getdist() {
cout << "nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void showdist() {
cout << feet << "' - " << inches << '"';
}
};
int main()
{
Distance dist; //define a named Distance object
dist.getdist(); //access object members
dist.showdist(); // with dot operator
Distance* distptr; //pointer to Distance
distptr = new Distance; //points to new Distance object
distptr->getdist(); //access object members
distptr->showdist(); // with -> operator
return 0;
}
Pointer to objects
// ok but inelegant
(*distptr).getdist();
// create Distance object (access with dot)
Distance& dist = *(new Distance);
7. #include <iostream>
using namespace std;
struct link //one element of list
{
int data; //data item
link *next; //pointer to next link
};
class linklist //a list of links
{
private:
link *first; //pointer to first link
public:
linklist() //no-argument constructor
{
first = NULL; //no first link
}
void additem(int d); //add data item (one link)
void display(); //display all links
};
void linklist::additem(int d) //add data item
{
link *newlink = new link; //make a new link
newlink -> data = d; //give it data
newlink -> next = first; //it points to next link
first = newlink; //now first points to this
}
void linklist::display() //display all links
{
link *current = first; //set ptr to first link
while (current != NULL) //quit on last link
{
cout << current -> data << endl; //print data
current = current -> next; //move to next link
}
}
int main()
{
linklist li; //make linked list
//add four items to list
li.additem(25);
li.additem(36);
li.additem(49);
li.additem(64);
li.display(); //display entire list
return 0;
}
Linked List
10. Virtual Functions
– Virtual means existing in appearance but not in reality.
– When virtual functions are used, a program that appears to be calling a
function of one class may in reality be calling a function of a different
class.
– Polymorphism means different forms.
11. #include <iostream>
using namespace std;
class Base //base class
{
public:
void show() {
cout << "Base Class.n";
}
};
class Derv1 : public Base //derived class 1
{
public:
void show() {
cout << "Derv1 Classn";
}
};
class Derv2 : public Base //derived class 2
{
public:
void show() {
cout << "Derv2 Classn";
}
};
int main()
{
Derv1 dv1; //object of derived class 1
Derv2 dv2; //object of derived class 2
Base *ptr; //pointer to base class
ptr = &dv1; //put address of dv1 in pointer
ptr -> show(); //execute show()
ptr = &dv2; //put address of dv2 in pointer
ptr -> show(); //execute show()
return 0;
}
Example 1
Normal Member Functions
Accessed with Pointers
13. #include <iostream>
using namespace std;
class Base //base class
{
public:
//virtual function
virtual void show() {
cout << "Base Classn";
}
};
class Derv1 : public Base //derived class 1
{
public:
void show() {
cout << "Derv1 Classn";
}
};
class Derv2 : public Base //derived class 2
{
public:
void show() {
cout << "Derv2 Classn";
}
};
int main()
{
Derv1 dv1; //object of derived class 1
Derv2 dv2; //object of derived class 2
Base *ptr; //pointer to base class
ptr = &dv1; //put address of dv1 in pointer
ptr -> show(); //execute show()
ptr = &dv2; //put address of dv2 in pointer
ptr -> show(); //execute show()
return 0;
}
Example 2
Virtual Member Functions
Accessed with Pointers
The same function call ptr -> show();
executes different functions, depending
on the contents of ptr.
14. Late/Dynamic Binding
– Which version of show() does the compiler call?
– In fact the compiler doesn’t know what to do, so it arranges for the decision to
be deferred until the program is running.
– At runtime, when it is known what class is pointed to by ptr, the appropriate
version of draw will be called. This is called late binding or dynamic binding.
– Choosing functions in the normal way, during compilation, is called early
binding or static binding.
– <
– Late binding requires some overhead but provides increased power and
flexibility.
15. Abstract Classes and Pure Virtual Functions
– When we will never want to instantiate objects of a base class, we call
it an abstract class.
– Such a class exists only to act as a parent of derived classes that will be
used to instantiate objects.
– It may also provide an interface for the class hierarchy.
– How can we can mark a class as abstract? By placing at least one pure
virtual function in the base class.
– A pure virtual function is one with the expression =0 added to the
declaration.
16. #include <iostream>
using namespace std;
class Base //base class
{
public:
virtual void show() = 0; //pure virtual function
};
class Derv1 : public Base //derived class 1
{
public:
void show() {
cout << "Derv1 Classn";
}
};
class Derv2 : public Base //derived class 2
{
public:
void show() {
cout << "Derv2 Classn";
}
};
int main()
{
// Base bad; //can’t make object from abstract class
Derv1 dv1; //object of derived class 1
Derv2 dv2; //object of derived class 2
Base *ptr; //pointer to base class
ptr = &dv1; //put address of dv1 in pointer
ptr-> show(); //execute show()
ptr = &dv2; //put address of dv2 in pointer
ptr -> show(); //execute show()
return 0;
}
Example 1
Pure Virtual
Function
Abstract Class
=0 expression
17. #include <iostream>
using namespace std;
class person //person class
{
protected:
char name[40];
public:
void getName() {
cout << " Enter name: "; cin >> name;
}
void putName() {
cout << "Name: " << name << endl;
}
virtual void getData() = 0; //pure virtual func
virtual bool isOutstanding() = 0; //pure virtual func
};
class student : public person //student class
{
private:
float gpa; //grade point average
public:
void getData() //get student data from user
{
person::getName();
cout << " Enter student's GPA: "; cin >> gpa;
}
bool isOutstanding() {
return (gpa > 3.5) ? true : false;
}
};
class professor : public person //professor class
{
private:
int numPubs; //number of papers published
public:
void getData() //get professor data from user
{
person::getName();
cout << " Enter number of professor's publications: ";
cin >> numPubs;
}
bool isOutstanding() {
return (numPubs > 100) ? true : false;
}
};
int main()
{
person *persPtr[100]; //array of pointers to persons
int n = 0; //number of persons on list
char choice;
do {
cout << "Enter student or professor (s/p): ";
cin >> choice;
if (choice == 's') //put new student
persPtr[n] = new student; // in array
else //put new professor
persPtr[n] = new professor; // in array
persPtr[n++] -> getData(); //get data for person
cout << " Enter another (y/n)? "; //do another person?
cin >> choice;
} while (choice == 'y'); //cycle until not ‘y’
//print names of all persons, and say if outstanding
for (int j = 0; j < n; j++)
{
persPtr[j] -> putName();
if (persPtr[j] -> isOutstanding())
cout << " This person is outstanding!n";
}
return 0;
}
Example 2
Pure Virtual
Function
Abstract Class
=0 expression
19. Friend Function
– A friend function is a function which operates on private data from
objects of two different classes.
– The function will take objects of the two classes as arguments and
operate on their private data.
20. #include <iostream>
using namespace std;
class beta; //needed for frifunc declaration
class alpha
{
private:
int data;
public:
alpha() : data(3)
{ }
friend int frifunc(alpha, beta); //friend function
};
class beta
{
private:
int data;
public:
beta() : data(7)
{ }
friend int frifunc(alpha, beta); //friend function
};
int frifunc(alpha a, beta b) //function definition
{
return (a.data + b.data);
}
int main()
{
alpha aa;
beta bb;
cout << frifunc(aa, bb) << endl; //call the function
return 0;
}
Example 1
Friend Function
21. #include <iostream>
using namespace std;
class Distance //English Distance class
{
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0)
{ }
Distance(float fltfeet) //convert float to Distance
{
feet = static_cast<int>(fltfeet); //feet is integer part
inches = 12 * (fltfeet - feet); //inches is what's left
}
Distance(int ft, float in) //constructor (two args)
{
feet = ft; inches = in;
}
void showdist() //display distance
{
cout << feet << "' - " << inches << '“’;
}
Distance operator + (Distance);
};
//add this distance to d2
Distance Distance::operator + (Distance d2) //return the sum
{
int f = feet + d2.feet; //add the feet
float i = inches + d2.inches; //add the inches
if (i >= 12.0) //if total exceeds 12.0
{
i -= 12.0;
f++;
}
return Distance(f, i); //return new Distance with sum
}
int main()
{
Distance d1 = 2.5; //constructor converts
Distance d2 = 1.25; //float feet to Distance
Distance d3;
cout << "nd1 = "; d1.showdist();
cout << "nd2 = "; d2.showdist();
d3 = d1 + 10.0; //distance + float: OK (Distance(float fltfeet) ctor)
cout << "nd3 = "; d3.showdist();
// d3 = 10.0 + d1; //float + Distance: ERROR
// cout << "nd3 = "; d3.showdist();
return 0;
}
Example 2
Without Friend
Function
22. #include <iostream>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
Distance() { //constructor no args
feet = 0; inches = 0.0;
}
Distance(float fltfeet) //constructor (one arg)
{ //convert float to Distance
feet = int(fltfeet); //feet is integer part
inches = 12 * (fltfeet - feet); //inches is what's left
}
Distance(int ft, float in) //constructor (two args)
{
feet = ft; inches = in;
}
void showdist() {
cout << feet << "' - " << inches << '“’;
}
friend Distance operator + (Distance, Distance); //friend
};
Distance operator + (Distance d1, Distance d2) //add d1 to d2
{
int f = d1.feet + d2.feet; //add the feet
float i = d1.inches + d2.inches; //add the inches
if (i >= 12.0) //if inches exceeds 12.0,
{
i -= 12.0;
f++;
}
return Distance(f, i); //return new Distance with sum
}
int main()
{
Distance d1 = 2.5; //constructor converts
Distance d2 = 1.25; //float-feet to Distance
Distance d3;
cout << "nd1 = "; d1.showdist();
cout << "nd2 = "; d2.showdist();
d3 = d1 + 10.0; //distance + float: OK
cout << "nd3 = "; d3.showdist();
d3 = 10.0 + d1; //float + Distance: OK
cout << "nd3 = "; d3.showdist();
return 0;
}
Example 3
Friend Function
A fix for the pervious
example
23. #include <iostream>
using namespace std;
//class beta;
class alpha
{
private:
int data1;
public:
alpha() : data1(99)
{ }
friend class beta; //beta is a friend class
//friend beta; // same (requires top definition)
};
class beta
{ //all member functions can access private alpha data
public:
void func1(alpha a) { cout << "ndata1 = " << a.data1; }
void func2(alpha a) { cout << "ndata1 = " << a.data1; }
};
int main()
{
alpha a;
beta b;
b.func1(a);
b.func2(a);
return 0;
}
Friend Classes
Example
Friend Class