This lecture covers overloaded functions, constant objects and member functions, friend functions, the this pointer, static data members, and composition with objects as members of classes. Specifically, it discusses:
1) Overloading constructors to initialize objects with different values.
2) Using const to declare objects, member functions, and data members as constant to prevent modification.
3) Defining member functions outside the class and using the scope resolution operator.
4) Passing objects as arguments to other functions and returning objects.
5) Using the this pointer implicitly and explicitly to access members of the current object.
6) Declaring static data members that are shared across all objects of a class.
The document discusses objects and classes in C++. It covers creating objects using new, constructors, destructors, accessor and mutator methods, default copy constructors, returning objects from functions, and variable scope. Specifically, it provides examples of creating Circle objects with constructors, defining destructors to deallocate memory, using getter and setter methods to access private data, and copying objects using the default copy constructor.
This document provides an overview of the C++ programming language. It discusses key C++ concepts like classes, objects, functions, and data types. Some key points:
- C++ is an object-oriented language that is an extension of C with additional features like classes and inheritance.
- Classes allow programmers to combine data and functions to model real-world entities. Objects are instances of classes.
- The document defines common C++ terms like keywords, identifiers, constants, and operators. It also provides examples of basic programs.
- Functions are described as modular and reusable blocks of code. Parameter passing techniques like pass-by-value and pass-by-reference are covered.
- Other concepts covered include
The document discusses inheritance and polymorphism in object-oriented programming. It defines inheritance as deriving a new subclass from a base class, creating a class hierarchy that shares code and interface. Polymorphism allows calling the same function on objects of different types and having the function call the appropriate implementation for that type. The document uses examples like student subclasses and shape classes to demonstrate inheritance and polymorphism implementation in C++ using virtual functions for dynamic binding.
Here are the key points about global, static and local objects:
- Global object constructors are called before main() and destructors after main() returns
- Local automatic objects are constructed when they are declared and destructed when they go out of scope
- Static local objects are constructed before main() and destructed after main() returns
- Objects declared within a function are local to that function
- The order of constructor/destructor calls follows the order of object declarations
So in summary, global and static objects persist for the duration of the program while local objects are temporary with lifetime of the block they are declared in.
The document discusses object oriented programming concepts like constructor overloading and objects as function arguments. It provides an example program using a Distance class with overloaded constructors to initialize objects in different ways. It demonstrates passing Distance objects to a member function add_dist() that calculates the total distance and stores it in a third Distance object.
The document discusses different types of variables and functions in C++. It provides examples of functions that take arguments, return values, and pass structures by reference. It also demonstrates overloaded functions, inline functions, default arguments, and the differences between automatic, external, and static variables. Various code snippets are included to illustrate how to declare, define, call, and pass variables and structures to functions in C++.
The document provides an introduction to programming in C++. It discusses the software development cycle including compiling, linking, and debugging programs. It also covers key programming concepts like variables, data types, functions, classes and objects. The evolution of C++ from C is described. Input/output statements like cout and cin are demonstrated along with basic program structure.
The document provides a 3-hour computer science exam containing multiple questions related to C++ programming. It includes questions about automatic type conversion vs type casting, header files, syntax errors, output of code snippets, polymorphism, class definitions, function definitions, arrays, memory allocation, stacks, and postfix notation evaluation.
This document contains 9 exercises demonstrating object-oriented programming concepts in C++ like classes, methods, constructors, and destructors. The exercises create classes to represent geometric shapes, birds, boxes, and more. Methods are defined to set and get data, calculate areas, and display output. Constructors and destructors are used to initialize and cleanup object memory.
This presentation covers C++ data types, variables, constants, and input/output. It discusses the different fundamental data types in C++ like int, char, float, and bool. It also explains variables, which name memory locations, constants, which are values that don't change, and input/output streams like cout and cin. The goal is for students to understand these basic C++ concepts and be able to write simple programs.
Classes and objects are key concepts in C++. A class defines the data and functions that can act on that data, while an object is an instance of a class. Classes contain public and private members to control access and promote reusability. Common tasks like initializing data, cleaning up memory, and accessing members are handled through constructors, destructors, and methods. Well-designed classes encapsulate data and behavior to be reused across programs while hiding implementation details. Examples demonstrate defining classes for counters, checkbooks, cans, and using built-in classes like string and file streams.
The document discusses classes and objects in object-oriented programming. It defines a class as a blueprint for objects that bind data and functions together. A class defines data members and member functions. Objects are instances of a class that can access class data and functions. The document provides examples of defining a class called "test" with private and public members, and creating objects of the class to demonstrate accessing members.
The document discusses constructors and destructors in C++. It explains that constructors initialize objects and are called automatically when an object is created. Constructors have the same name as the class and do not have a return type. Destructors are called when an object is destroyed to deallocate memory. The document provides an example of a Distance class with overloaded constructors and a member function to add distances defined outside the class.
This document provides an overview of data types in C++. It discusses fundamental data types like int, char, float, and void, as well as derived data types like arrays, functions, pointers, references, constants, classes, structures, unions, and enumerations. For each data type, it provides examples and explanations of how they are used and represented in memory. It also covers data type modifiers, variable declaration and initialization, and input/output stream manipulators for formatting output.
The document provides an introduction to programming fundamentals in C++, including basic syntax and components of a C++ program. It covers variables and data types, input/output, comments, and how to write a simple C++ program with preprocessor directives and a main function. The key topics discussed are variable declaration, fundamental data types like int, float, char, comments, and how to write a basic "Hello World" program in C++.
The document provides an overview of the C++ programming language. It discusses that C++ was created by Bjarne Stroustrup to provide Simula's facilities for program organization together with C's efficiency and flexibility for systems programming. The document outlines key C++ features like classes, templates, operator overloading, and exceptions. It also covers topics like class definitions, constructors, destructors, streams, and compiling/linking C++ programs.
The document provides examples of using friend functions in C++.
In the first example, a friend function "add()" is declared and defined to access private members of class "Sum" to add two numbers. The second example demonstrates how a friend function "fun()" can access private members of two different classes "A" and "B". The third example shows how a static member function and static data member can be accessed using the class name and scope resolution operator.
This document provides an overview of key concepts in C++ including classes, objects, encapsulation, inheritance, and pointers. It discusses how classes can be used to model real-world entities, hiding implementation details and exposing only necessary functions. Inheritance allows code reuse by deriving specialized classes from general base classes. Pointers store the address of variables in memory and can be used to pass data between functions by reference. The document also provides an example Student class with member variables and functions to set and retrieve student data like GPA.
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 2 (20)
The document discusses object oriented programming concepts like constructor overloading and objects as function arguments. It provides an example program using a Distance class with overloaded constructors to initialize objects in different ways. It demonstrates passing Distance objects to a member function add_dist() that calculates the total distance and stores it in a third Distance object.
The document discusses different types of variables and functions in C++. It provides examples of functions that take arguments, return values, and pass structures by reference. It also demonstrates overloaded functions, inline functions, default arguments, and the differences between automatic, external, and static variables. Various code snippets are included to illustrate how to declare, define, call, and pass variables and structures to functions in C++.
The document provides an introduction to programming in C++. It discusses the software development cycle including compiling, linking, and debugging programs. It also covers key programming concepts like variables, data types, functions, classes and objects. The evolution of C++ from C is described. Input/output statements like cout and cin are demonstrated along with basic program structure.
The document provides a 3-hour computer science exam containing multiple questions related to C++ programming. It includes questions about automatic type conversion vs type casting, header files, syntax errors, output of code snippets, polymorphism, class definitions, function definitions, arrays, memory allocation, stacks, and postfix notation evaluation.
This document contains 9 exercises demonstrating object-oriented programming concepts in C++ like classes, methods, constructors, and destructors. The exercises create classes to represent geometric shapes, birds, boxes, and more. Methods are defined to set and get data, calculate areas, and display output. Constructors and destructors are used to initialize and cleanup object memory.
This presentation covers C++ data types, variables, constants, and input/output. It discusses the different fundamental data types in C++ like int, char, float, and bool. It also explains variables, which name memory locations, constants, which are values that don't change, and input/output streams like cout and cin. The goal is for students to understand these basic C++ concepts and be able to write simple programs.
Classes and objects are key concepts in C++. A class defines the data and functions that can act on that data, while an object is an instance of a class. Classes contain public and private members to control access and promote reusability. Common tasks like initializing data, cleaning up memory, and accessing members are handled through constructors, destructors, and methods. Well-designed classes encapsulate data and behavior to be reused across programs while hiding implementation details. Examples demonstrate defining classes for counters, checkbooks, cans, and using built-in classes like string and file streams.
The document discusses classes and objects in object-oriented programming. It defines a class as a blueprint for objects that bind data and functions together. A class defines data members and member functions. Objects are instances of a class that can access class data and functions. The document provides examples of defining a class called "test" with private and public members, and creating objects of the class to demonstrate accessing members.
The document discusses constructors and destructors in C++. It explains that constructors initialize objects and are called automatically when an object is created. Constructors have the same name as the class and do not have a return type. Destructors are called when an object is destroyed to deallocate memory. The document provides an example of a Distance class with overloaded constructors and a member function to add distances defined outside the class.
This document provides an overview of data types in C++. It discusses fundamental data types like int, char, float, and void, as well as derived data types like arrays, functions, pointers, references, constants, classes, structures, unions, and enumerations. For each data type, it provides examples and explanations of how they are used and represented in memory. It also covers data type modifiers, variable declaration and initialization, and input/output stream manipulators for formatting output.
The document provides an introduction to programming fundamentals in C++, including basic syntax and components of a C++ program. It covers variables and data types, input/output, comments, and how to write a simple C++ program with preprocessor directives and a main function. The key topics discussed are variable declaration, fundamental data types like int, float, char, comments, and how to write a basic "Hello World" program in C++.
The document provides an overview of the C++ programming language. It discusses that C++ was created by Bjarne Stroustrup to provide Simula's facilities for program organization together with C's efficiency and flexibility for systems programming. The document outlines key C++ features like classes, templates, operator overloading, and exceptions. It also covers topics like class definitions, constructors, destructors, streams, and compiling/linking C++ programs.
The document provides examples of using friend functions in C++.
In the first example, a friend function "add()" is declared and defined to access private members of class "Sum" to add two numbers. The second example demonstrates how a friend function "fun()" can access private members of two different classes "A" and "B". The third example shows how a static member function and static data member can be accessed using the class name and scope resolution operator.
This document provides an overview of key concepts in C++ including classes, objects, encapsulation, inheritance, and pointers. It discusses how classes can be used to model real-world entities, hiding implementation details and exposing only necessary functions. Inheritance allows code reuse by deriving specialized classes from general base classes. Pointers store the address of variables in memory and can be used to pass data between functions by reference. The document also provides an example Student class with member variables and functions to set and retrieve student data like GPA.
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!
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.
Artificial Intelligence Applications Across IndustriesSandeepKS52
Artificial Intelligence is a rapidly growing field that influences many aspects of modern life, including transportation, healthcare, and finance. Understanding the basics of AI provides insight into how machines can learn and make decisions, which is essential for grasping its applications in various industries. In the automotive sector, AI enhances vehicle safety and efficiency through advanced technologies like self-driving systems and predictive maintenance. Similarly, in healthcare, AI plays a crucial role in diagnosing diseases and personalizing treatment plans, while in financial services, it helps in fraud detection and risk management. By exploring these themes, a clearer picture of AI's transformative impact on society emerges, highlighting both its potential benefits and challenges.
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.
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...WSO2
Enterprises must deliver intelligent, cloud native applications quickly—without compromising governance or scalability. This session explores how an internal developer platform increases productivity via AI for code and accelerates AI-native app delivery via code for AI. Learn practical techniques for embedding AI in the software lifecycle, automating governance with AI agents, and applying a cell-based architecture for modularity and scalability. Real-world examples and proven patterns will illustrate how to simplify delivery, enhance developer productivity, and drive measurable outcomes.
Learn more: https://wso2.com/choreo
14 Years of Developing nCine - An Open Source 2D Game FrameworkAngelo Theodorou
A 14-year journey developing nCine, an open-source 2D game framework.
This talk covers its origins, the challenges of staying motivated over the long term, and the hurdles of open-sourcing a personal project while working in the game industry.
Along the way, it’s packed with juicy technical pills to whet the appetite of the most curious developers.
Best Inbound Call Tracking Software for Small BusinessesTheTelephony
The best inbound call tracking software for small businesses offers features like call recording, real-time analytics, lead attribution, and CRM integration. It helps track marketing campaign performance, improve customer service, and manage leads efficiently. Look for solutions with user-friendly dashboards, customizable reporting, and scalable pricing plans tailored for small teams. Choosing the right tool can significantly enhance communication and boost overall business growth.
Bonk coin airdrop_ Everything You Need to Know.pdfHerond Labs
The Bonk airdrop, one of the largest in Solana’s history, distributed 50% of its total supply to community members, significantly boosting its popularity and Solana’s network activity. Below is everything you need to know about the Bonk coin airdrop, including its history, eligibility, how to claim tokens, risks, and current status.
https://blog.herond.org/bonk-coin-airdrop/
GDG Douglas - Google AI Agents: Your Next Intern?felipeceotto
Presentation done at the GDG Douglas event for June 2025.
A first look at Google's new Agent Development Kit.
Agent Development Kit is a new open-source framework from Google designed to simplify the full stack end-to-end development of agents and multi-agent systems.
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.
FME as an Orchestration Tool - Peak of Data & AI 2025Safe Software
Processing huge amounts of data through FME can have performance consequences, but as an orchestration tool, FME is brilliant! We'll take a look at the principles of data gravity, best practices, pros, cons, tips and tricks. And of course all spiced up with relevant examples!
Who will create the languages of the future?Jordi Cabot
Will future languages be created by language engineers?
Can you "vibe" a DSL?
In this talk, we will explore the changing landscape of language engineering and discuss how Artificial Intelligence and low-code/no-code techniques can play a role in this future by helping in the definition, use, execution, and testing of new languages. Even empowering non-tech users to create their own language infrastructure. Maybe without them even realizing.
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.
Integration Ignited Redefining Event-Driven Architecture at Wix - EventCentricNatan Silnitsky
At Wix, we revolutionized our platform by making integration events the backbone of our 4,000-microservice ecosystem. By abandoning traditional domain events for standardized Protobuf events through Kafka, we created a universal language powering our entire architecture.
We'll share how our "single-aggregate services" approach—where every CUD operation triggers semantic events—transformed scalability and extensibility, driving efficient event choreography, data lake ingestion, and search indexing.
We'll address our challenges: balancing consistency with modularity, managing event overhead, and solving consumer lag issues. Learn how event-based data prefetches dramatically improved performance while preserving the decoupling that makes our platform infinitely extensible.
Key Takeaways:
- How integration events enabled unprecedented scale and extensibility
- Practical strategies for event-based data prefetching that supercharge performance
- Solutions to common event-driven architecture challenges
- When to break conventional architectural rules for specific contexts
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfVarsha Nayak
In recent years, organizations have increasingly sought robust open source alternative to Jasper Reports as the landscape of open-source reporting tools rapidly evolves. While Jaspersoft has been a longstanding choice for generating complex business intelligence and analytics reports, factors such as licensing changes and growing demands for flexibility have prompted many businesses to explore other options. Among the most notable alternatives to Jaspersoft, Helical Insight stands out for its powerful open-source architecture, intuitive analytics, and dynamic dashboard capabilities. Designed to be both flexible and budget-friendly, Helical Insight empowers users with advanced features—such as in-memory reporting, extensive data source integration, and customizable visualizations—making it an ideal solution for organizations seeking a modern, scalable reporting platform. This article explores the future of open-source reporting and highlights why Helical Insight and other emerging tools are redefining the standards for business intelligence solutions.
Insurance policy management software transforms complex, manual insurance operations into streamlined, efficient digital workflows, enhancing productivity, accuracy, customer service, and profitability for insurers. Visit https://www.damcogroup.com/insurance/policy-management-software for more details!
4. #include <iostream>
using namespace std;
class smallobj {
private:
int somedata;
public:
void setdata(int d) {
somedata = d;
}
void showdata() {
cout << "Data is " << somedata << endl;
}
};
int main() {
smallobj s1;
s1.setdata(1066);
s1.showdata();
return 0;
}
5. #include <iostream>
using namespace std;
//English Distance class
class Distance {
private:
int feet;
float inches;
public:
//constructor (no args)
Distance() : feet(0), inches(0.0)
{ }
//constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() { //get length from user
cout << "nEnter feet : "; cin >> feet;
cout << "Enter inches : "; cin >> inches;
}
void showdist() { //display distance
cout << feet << "' - " << inches << '"';
}
void add_dist(Distance, Distance); //declaration
};
//add lengths d2 and d3
void Distance::add_dist(Distance d2, Distance d3) {
inches = d2.inches + d3.inches; //add the inches
feet = 0; //(for possible carry)
if (inches >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
inches -= 12.0; //by 12.0 and
feet++; //increase feet by 1
}
feet += d2.feet + d3.feet; //add the feet
}
int main()
{
Distance dist1, dist3; //define two lengths
Distance dist2(11, 6.25); //define and initialize dist2
dist1.getdist(); //get dist1 from user
dist3.add_dist(dist1, dist2); //dist3 = dist1 + dist2
//display all lengths
cout << "ndist1 = ";
dist1.showdist();
cout << "ndist2 = ";
dist2.showdist();
cout << "ndist3 = ";
dist3.showdist();
cout << endl;
return 0;
}
6. Member Functions
Defined Outside the
Class
– So far we’ve seen member functions
defined inside the class definition.
– However, we can define member
functions outsize the class.
7. #include <iostream>
using namespace std;
// English Distance class
class Distance
{
private:
int feet;
float inches;
public:
Distance() : feet(0), inches(0.0) //constructor (no args)
{ }
Distance(int ft, float in) : feet(ft), inches(in) //constructor (two args)
{ }
void getdist() {
cout << "nEnter feet : ";
cin >> feet;
cout << "Enter inches : ";
cin >> inches;
}
void showdist() {
cout << feet << "' - " << inches << '"';
}
void add_dist(Distance, Distance); //declaration
};
void Distance::add_dist(Distance d2, Distance d3)
{
inches = d2.inches + d3.inches; //add the inches
feet = 0; //(for possible carry)
if (inches >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
inches -= 12.0; //by 12.0 and
feet++; //increase feet by 1
}
feet += d2.feet + d3.feet; //add the feet
}
Example
Objects as arguments
9. const Member Functions
– A const member function guarantees that it will never modify any of its class’s
member data.
– A function is made into a constant function by placing the keyword const after
the declarator but before the function body.
class Example
{
private:
int alpha;
public:
void nonFunc() //non-const member function
{
alpha = 99; //OK
}
void conFunc() const //const member function
{
alpha = 99; //ERROR: can’t modify a member
}
};
Member functions that do nothing
but acquire data from an object are
obvious candidates for being made
const, because they don’t need to
modify any data.
10. const Objects
– In several example programs, we’ve seen that we can apply const to
variables of basic types such as int to keep them from being modified.
– In a similar way, we can apply const to objects of classes. When an object
is declared as const, you can’t modify it.
– It follows that you can use only const member functions with it, because
they’re the only ones that guarantee not to modify it.
12. #include <iostream>
using namespace std;
class Distance //English Distance class
{
private:
int feet;
float inches;
public:
//constructor (no args)
Distance() : feet(0), inches(0.0)
{ }
//constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() {
cout << "nEnter feet : "; cin >> feet;
cout << "Enter inches : "; cin >> inches;
}
void showdist() {
cout << feet << "' - " << inches << '"';
}
Distance add_dist(Distance); //add
};
//--------------------------------------------------------------
//add this distance to d2, return the sum
Distance Distance::add_dist(Distance d2)
{
Distance temp; //temporary variable
temp.inches = inches + d2.inches; //add the inches
if (temp.inches >= 12.0) //if total exceeds 12.0,
{ //then decrease inches
temp.inches -= 12.0; //by 12.0 and
temp.feet = 1; //increase feet by 1
}
temp.feet += feet + d2.feet; //add the feet
return temp;
}
int main()
{
Distance dist1, dist3; //define two lengths
Distance dist2(11, 6.25); //define, initialize dist2
dist1.getdist(); //get dist1 from user
dist3 = dist1.add_dist(dist2); //dist3 = dist1 + dist2
//display all lengths
cout << "ndist1 = ";
dist1.showdist();
cout << "ndist2 = ";
dist2.showdist();
cout << "ndist3 = ";
dist3.showdist();
cout << endl;
return 0;
}
Returning
Objects
from
Functions
14. #include <iostream>
using namespace std;
enum Suit { clubs, diamonds, hearts, spades };
const int jack = 11; //from 2 to 10 are
const int queen = 12; //integers without names
const int king = 13;
const int ace = 14;
class card
{
private:
int number; //2 to 10, jack, queen, king, ace
Suit suit; //clubs, diamonds, hearts, spades
public:
card() //constructor (no args)
{ }
//constructor (two args)
card(int n, Suit s) : number(n), suit(s)
{ }
void display(); //display card
bool isEqual(card); //same as another card?
};
void card::display() //display the card
{
if (number >= 2 && number <= 10)
cout << number << " of ";
else
switch (number)
{
case jack:
cout << "jack of ";
break;
case queen:
cout << "queen of ";
break;
case king:
cout << "king of ";
break;
case ace:
cout << "ace of ";
break;
}
switch (suit)
{
case clubs: cout << "clubs"; break;
case diamonds: cout << "diamonds"; break;
case hearts: cout << "hearts"; break;
case spades: cout << "spades"; break;
}
}
bool card::isEqual(card c2) //return true if cards equal
{
return (number == c2.number && suit == c2.suit) ? true : false;
}
int main()
{
card temp, chosen, prize; //define various cards
int position;
card card1(7, clubs); //define & initialize card1
cout << "nCard 1 is the ";
card1.display(); //display card1
card card2(jack, hearts); //define & initialize card2
cout << "nCard 2 is the ";
card2.display(); //display card2
card card3(ace, spades); //define & initialize card3
cout << "nCard 3 is the ";
card3.display(); //display card3
prize = card3; //prize is the card to guess
cout << "nI'm swapping card 1 and card 3";
temp = card3;
card3 = card1;
card1 = temp;
cout << "nI'm swapping card 2 and card 3";
temp = card3;
card3 = card2;
card2 = temp;
cout << "nI'm swapping card 1 and card 2";
temp = card2;
card2 = card1;
card1 = temp;
cout << "nNow, where (1, 2, or 3) is the ";
prize.display(); //display prize card
cout << " ? ";
cin >> position; //get user’s guess of position
switch (position)
{ //set chosen to user’s choice
case 1:
chosen = card1;
break;
case 2:
chosen = card2;
break;
case 3:
chosen = card3;
break;
}
if (chosen.isEqual(prize)) //is chosen card the prize?
cout << "That's right! You win!";
else
cout << "Sorry. You lose.";
cout << " You chose the ";
chosen.display(); //display chosen card
cout << endl;
return 0;
}
A Card-
Game
Example
15. The Standard C++ string Class
#include <iostream>
#include <string> //for string class
using namespace std;
int main()
{ //objects of string class
string full_name, nickname, address;
string greeting("Hello, ");
cout << "Enter your full name : ";
getline(cin, full_name); //reads embedded blanks
cout << "Your full name is : " << full_name << endl;
cout << "Enter your nickname : ";
cin >> nickname; //input to string object
greeting += nickname; //append name to greeting
cout << greeting << endl; //output: "Hello, Mohamed"
cout << "Enter your address on separate linesn";
cout << "Terminate with '$'n";
getline(cin, address, '$'); //reads multiple lines
cout << "Your address is : " << address << endl;
return 0;
}
17. #include <iostream>
#include <cstring> // for strcpy(), strcat()
using namespace std;
class String
{
private:
enum { SZ = 80 }; //max size of Strings
char str[SZ]; //array
public:
String() //constructor, no args
{
str[0] = '0’;
}
String(char s[]) //constructor, one arg
{
strcpy(str, s);
}
void display() //display string
{
cout << str;
}
void concat(String s2) //add arg string to this string
{
if (strlen(str) + strlen(s2.str) < SZ)
strcat(str, s2.str);
else
cout << "nString is too long!";
}
};
int main()
{
String s1("Merry Christmas!"); //uses constructor 2
String s2 = "Season's Greetings!"; //alternate form of 2
String s3; //uses constructor 1
//display them all
cout << "ns1 = ";
s1.display();
cout << "ns2 = ";
s2.display();
cout << "ns3 = ";
s3.display();
s3 = s1; //assignment
cout << "ns3 = "; //display s3 before
s3.display();
s3.concat(s2); //concatenation
cout << "ns3 = "; //display s3 after
s3.display();
return 0;
}
String
Class
Example 3
18. #include <iostream>
#include <string>
using namespace std;
int main() {
string s1("Quick! Send for Count Graystone.");
string s2("Lord");
string s3("Don't ");
s1.erase(0, 7); //remove "Quick! " → "Send for Count Graystone."
s1.replace(16, 5, s2); //replace "Count" with "Lord"
s1.replace(7, 1, "s"); //replace 'S' with 's’
s1.insert(0, s3); //insert "Don't " at beginning
s1.erase(s1.size() - 1, 1); //remove '.' (30)
s1.append(3, '!'); //append "!!!"
int x = s1.find(' '); //find a space (6)
while (x < s1.size()) //loop while spaces remain
{
s1.replace(x, 1, "/"); //replace with slash
x = s1.find(' '); //find next space (11, 15, 21)
}
cout << "s1: " << s1 << endl;
return 0;
}
String Class
Example 4
19. #include <iostream>
#include <string>
using namespace std;
int main() {
string aName = "Mohamed";
string userName;
cout << "Enter your first name: ";
cin >> userName;
if (userName == aName) //operator ==
cout << "Greetings, " << userName << endl;
else if (userName < aName) //operator <
cout << "You come before Mohamed" << endl;
else
cout << "You come after Mohamed" << endl;
//compare() function
int n = userName.compare(0, 2, aName, 0, 2);
cout << "The first two letters of your name ";
if (n == 0)
cout << "match ";
else if (n < 0)
cout << "come before ";
else
cout << "come after ";
cout << aName.substr(0, 2) << endl;
return 0;
}
String Class
Example 5
compare()
20. #include <iostream>
#include <string>
using namespace std;
int main()
{
char charray[80];
string word;
cout << "Enter a word: ";
cin >> word;
//getline(cin, word);
int wlen = word.length(); //length of string object
// int wlen = word.size();
cout << "One character at a time: ";
for (int j = 0; j < wlen; j++)
cout << word.at(j); //exception if out-of-bounds
// cout << word[j]; //no warning if out-of-bounds
word.copy(charray, wlen, 0); //copy string object to array
charray[wlen] = 0; //terminate with ‘0’
cout << "nArray contains: " << charray << endl;
return 0;
}
String Class
Example 6
Accessing Characters
in string Objects using
the overloaded []
operator
21. Structures and Classes
– The only formal difference between class and struct is that in a class the
members are private by default, while in a structure they are public by
default.
class foo {
private:
int data1;
public:
void func();
};
class foo {
private:
int data1;
public:
void func();
};
22. #include <iostream>
using namespace std;
class Stack
{
private:
enum { MAX = 10 }; //(non-standard syntax)
int st[MAX]; //stack: array of integers
int top; //number of top of stack
public:
Stack() //constructor
{
top = 0;
}
void push(int var) //put number on stack
{
st[++top] = var;
}
int pop() //take number off stack
{
return st[top--];
}
};
int main()
{
Stack s1;
s1.push(11);
s1.push(22);
cout << "1: " << s1.pop() << endl; //22
cout << "2: " << s1.pop() << endl; //11
s1.push(33);
s1.push(44);
s1.push(55);
s1.push(66);
cout << "3: " << s1.pop() << endl; //66
cout << "4: " << s1.pop() << endl; //55
cout << "5: " << s1.pop() << endl; //44
cout << "6: " << s1.pop() << endl; //33
return 0;
}
Stack
24. Operator Overloading
– Operator overloading gives you the opportunity to redefine the C++ language.
– The term operator overloading refers to giving the normal C++ operators such
as +, *, <=, and +=, additional meanings when they are applied to user-defined
data types.
– Another kind of operation, data type conversion, is closely connected with
operator overloading.
– C++ handles the conversion of simple types, such as int and float,
automatically; but conversions involving user-defined types require some work
on the programmer’s part.
25. 1) Unary Operator Overloading
– Unary operators act on only one operand. (An operand is simply a
variable acted on by an operator).
– Examples of unary operators are the increment and decrement
operators ++ and --, and the unary minus, as in -33
26. #include <iostream>
using namespace std;
class Counter {
private:
unsigned int count;
public:
Counter() : count(0) //constructor
{ }
unsigned int get_count() //return count
{
return count;
}
void operator ++ () //increment (prefix)
{
count++;
}
};
int main() {
Counter c1, c2; //define and initialize
cout << "nc1 = " << c1.get_count(); //display
cout << "nc2 = " << c2.get_count();
++c1; //increment c1
++c2; //increment c2
++c2; //increment c2
cout << "nc1 = " << c1.get_count(); //display again
cout << "nc2 = " << c2.get_count() << endl;
return 0;
}
Example 1
A subtle defect
if you use the
statement:
'c1 = ++c2'
(Prefix)
27. #include <iostream>
using namespace std;
class Counter
{
private:
unsigned int count;
public:
Counter() : count(0) //constructor
{ }
unsigned int get_count() //return count
{
return count;
}
Counter operator ++ () //increment count
{
++count; //increment count
Counter temp; //make a temporary Counter
temp.count = count; //give it same value as this obj
return temp; //return the copy
}
};
int main()
{
Counter c1, c2; //c1=0, c2=0
cout << "nc1 = " << c1.get_count(); //display
cout << "nc2 = " << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2
cout << "nc1 = " << c1.get_count(); //display again
cout << "nc2 = " << c2.get_count() << endl;
return 0;
}
Example 2
Solution
28. #include <iostream>
using namespace std;
class Counter
{
private:
unsigned int count;
public:
Counter() : count(0) //constructor no args
{ }
Counter(int c) : count(c) //constructor, one arg
{ }
unsigned int get_count() //return count
{
return count;
}
Counter operator ++ () //increment count
{
++count; // increment count, then return
return Counter(count); // an unnamed temporary object
} // initialized to this count
};
int main()
{
Counter c1, c2; //c1=0, c2=0
cout << "nc1 = " << c1.get_count(); //display
cout << "nc2 = " << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2
cout << "nc1 = " << c1.get_count(); //display again
cout << "nc2 = " << c2.get_count() << endl;
return 0;
}
Example 2
Solution 2
29. #include <iostream>
using namespace std;
class Counter
{
private:
unsigned int count; //count
public:
Counter() : count(0) //constructor no args
{ }
Counter(int c) : count(c) //constructor, one arg
{ }
unsigned int get_count() const //return count
{
return count;
}
Counter operator ++ () //increment count (prefix)
{
return Counter(++count);
}
Counter operator ++ (int) //increment count (postfix)
{
return Counter(count++);
}
};
int main()
{
Counter c1, c2; //c1=0, c2=0
cout << "nc1 = " << c1.get_count(); //display
cout << "nc2 = " << c2.get_count();
++c1; //c1=1
c2 = ++c1; //c1=2, c2=2 (prefix)
cout << "nc1 = " << c1.get_count(); //display
cout << "nc2 = " << c2.get_count();
c2 = c1++; //c1=3, c2=2 (postfix)
cout << "nc1 = " << c1.get_count(); //display again
cout << "nc2 = " << c2.get_count() << endl;
return 0;
}
Example 3
(Prefix and Postfix)
int is a signal to indicate postfix
✓ You can use this same approach
with the decrement operator (--)
as well.
30. 2) Overloading Binary Operators
– Binary operators can be overloaded just as easily as unary operators.
– We’ll look at examples that overload arithmetic operators, comparison
operators, and arithmetic assignment operators.
31. #include <iostream>
using namespace std;
class Distance //English Distance class
{
private:
int feet;
float inches;
public: //constructor (no args)
Distance() : feet(0), inches(0.0)
{ }
//constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() //get length from user
{
cout << "nEnter feet : "; cin >> feet;
cout << "Enter inches : "; cin >> inches;
}
void showdist() const //display distance
{
cout << feet << "' - " << inches << '"';
}
Distance operator + (Distance) const; //add 2 distances
};
//add this distance to d2
Distance Distance::operator + (Distance d2) const //return 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
{ //then decrease inches by 12.0 and increase feet by 1
i -= 12.0;
f++;
}
return Distance(f, i); //return a temporary Distance initialized to sum
}
int main()
{
Distance dist1, dist3, dist4; //define distances
dist1.getdist(); //get dist1 from user
Distance dist2(11, 6.25); //define, initialize dist2
dist3 = dist1 + dist2; //single ‘+’ operator
dist4 = dist1 + dist2 + dist3; //multiple ‘+’ operators
//display all lengths
cout << "dist1 = "; dist1.showdist(); cout << endl;
cout << "dist2 = "; dist2.showdist(); cout << endl;
cout << "dist3 = "; dist3.showdist(); cout << endl;
cout << "dist4 = "; dist4.showdist(); cout << endl;
return 0;
}
Example 1 Output:
32. #include <iostream>
#include <string.h> //for strcpy(), strcat()
#include <stdlib.h> //for exit()
using namespace std;
class String //user-defined string type
{
private:
enum { SZ = 80 }; //size of String objects
char str[SZ]; //holds a string
public:
String() //constructor, no args
{
strcpy(str, "");
}
String(char s[]) //constructor, one arg
{
strcpy(str, s);
}
void display() const //display the String
{
cout << str;
}
String operator + (String ss) const //add Strings
{
String temp; //make a temporary String
if (strlen(str) + strlen(ss.str) < SZ)
{
strcpy(temp.str, str); //copy this string to temp
strcat(temp.str, ss.str); //add the argument string
}
else
{
cout << "nString overflow"; exit(1);
}
return temp; //return temp String
}
};
int main()
{
String s1 = "nHello, Mohamed!"; //uses constructor 2
String s2 = "Welcome abroad."; //uses constructor 2
String s3; //uses constructor 1
s1.display(); //display strings
s2.display();
s3.display();
s3 = s1 + s2; //add s2 to s1, assign to s3
s3.display(); //display s3
return 0;
}
Example 2
(String Class)
33. 3) Overloading Comparison Operator
– The following example overloads the less than operator (<) in the
Distance class in order to be used in comparing two distances.
38. #include <iostream>
#include <process.h> // for exit()
using namespace std;
const int LIMIT = 5;
class safearay
{
private:
int arr[LIMIT];
public:
void putel(int n, int elvalue) //set value of element
{
if (n < 0 || n >= LIMIT) {
cout << "Index out of bounds.";
exit(1);
}
arr[n] = elvalue;
}
int getel(int n) const //get value of element
{
if (n < 0 || n >= LIMIT)
{
cout << "Index out of bounds.";
exit(1);
}
return arr[n];
}
};
int main()
{
safearay sa1;
for (int i = 0; i < LIMIT; i++) // insert elements
sa1.putel(i, i * 10);
for (int i = 0; i < LIMIT; i++) // display elements
cout << "Element " << i << " is " << sa1.getel(i) << endl;
return 0;
}
Safe Array
Class
Example 1
39. #include <iostream>
#include <process.h> //for exit()
using namespace std;
const int LIMIT = 5; //array size
class safearay
{
private:
int arr[LIMIT];
public:
int& operator [] (int n) //note: return by reference
{
if (n < 0 || n >= LIMIT)
{
cout << "Index out of bounds.";
exit(1);
}
return arr[n];
}
};
int main()
{
safearay sa1;
for (int i = 0; i < LIMIT; i++) //insert elements
sa1[i] = i * 10;
for (int i = 0; i < LIMIT; i++) //display elements
cout << "Element " << i << " is " << sa1[i] << endl;
return 0;
}
Safe Array
Class
Example 2
Overloading the subscript [ ]
operator
40. The Standard C++ string Class
#include <iostream>
#include <string> //for string class
using namespace std;
int main()
{ //objects of string class
string full_name, nickname, address;
string greeting("Hello, ");
cout << "Enter your full name : ";
getline(cin, full_name); //reads embedded blanks
cout << "Your full name is : " << full_name << endl;
cout << "Enter your nickname : ";
cin >> nickname; //input to string object
greeting += nickname; //append name to greeting
cout << greeting << endl; //output: "Hello, Mohamed"
cout << "Enter your address on separate linesn";
cout << "Terminate with '$'n";
getline(cin, address, '$'); //reads multiple lines
cout << "Your address is : " << address << endl;
return 0;
}
42. Operator Overloading – Summary
– Use similar meanings (i.e., semantics), you could overload the + sign to perform
subtraction, for example, but that would hardly make your listings more
comprehensible.
– You can’t overload a binary operator to be a unary operator, or vice versa.
– Not all operators can be overloaded, the following operators cannot be
overloaded:
▪ the member access or dot operator (.)
▪ the scope resolution operator (::)
▪ the conditional operator (?:)
▪ the pointer-to-member operator (->)
▪ you can’t create new operators (like *&) and try to overload them; only existing operators
can be overloaded.