Templates allow functions and classes to work with different data types. Template classes define generic class definitions that can be used for multiple types, while template functions define generic functions. When a template is instantiated, actual code is generated for the specific types used. Exceptions provide a mechanism to handle runtime errors in C++ and are used by enclosing code that may throw exceptions in a try block and catching specific exceptions in catch blocks.
The document discusses function templates and class templates in C++. It provides examples of defining function templates that can handle arguments and return values of different data types. It also demonstrates how to define class templates where the class can work with variables of different types. The key points are:
1. Function templates allow functions to handle arguments and return values of different data types. Class templates make a class work for variables of any type instead of a single data type.
2. Examples show how to define template functions that can accept and return values of int, float and other types. Class templates are also defined that can work with objects of int and float types.
3. The document discusses how template functions and classes are
The document discusses function templates and class templates in C++. It provides examples of defining function templates that can handle arguments and return values of different data types. It also demonstrates how to define class templates where the class can work with variables of different types. The key points are:
1. Function templates allow functions to handle arguments and return values of different data types. Class templates make a class work for variables of any type instead of a single data type.
2. Examples show how to define template functions that can accept and return values of int, float and other types. Class templates are also defined that can work with objects of int and float types.
3. The document explains how to define member functions for
The document discusses several advanced C++ programming concepts including abstract classes, exception handling, standard libraries, templates, and containers. It defines abstract classes as classes that contain pure virtual functions and cannot be instantiated. Exception handling allows programs to continue running or terminate gracefully after errors using try, catch, and throw blocks. The standard library provides common functions and classes for input/output, strings, and containers. Templates allow writing generic and reusable code for different data types, including class templates and function templates. The Standard Template Library includes common containers like vectors, lists, and maps that store and organize data using templates and iterators.
Templates may be used in many combinations with inheritance. It is possible to combine inheritance and templates because a template class is a class, albeit one with a parameter. Combining these language features allows the parameterization ability of templates to be used in conjunction with the specializing abilities of inheritance. Four combinations of templates and inheritance are presented in this section:
a template class that inherits from another template class,
a non-template class that inherits from a template class,
a template class that inherits from a non-template class, and
a template class that uses multiple inheritance.
Each of these combinations will be illustrated by an example showing how the two features are combined and what advantages are possibly gained by using them together.
This document contains code snippets for 12 common C++ programs: 1) checking if a number is even or odd, 2) swapping two numbers, 3) checking if a year is a leap year, 4) sorting words in dictionary order, 5) calculating a factorial, 6) generating a Fibonacci series, 7) transposing a matrix, 8) using constructors and destructors, 9) demonstrating multiple inheritance, 10) using static members and functions, 11) exception handling, and 12) file input/output. Each code snippet is followed by sample input/output to demonstrate the program's functionality.
Day 1 of the training covers introductory C++ concepts like object-oriented programming, compilers, IDEs, classes, objects, and procedural programming concepts. Day 2 covers more advanced class concepts like constructors, destructors, static members, returning objects, and arrays of objects. Day 3 covers function and operator overloading.
C++ allows for concise summaries in 3 sentences or less:
The document provides an overview of C++ concepts including data types, variables, operators, functions, classes, inheritance and virtual members. It also covers process and thread concepts at a high level. Code examples are provided to illustrate namespaces, input/output, program flow control, overloading, dynamic memory allocation, and classes. The document serves as a brief review of fundamental C++ and system programming concepts.
This document provides an overview of the C++ Data Structures lab manual. It covers topics like C++ review, implementation of various data structures like stack, queue, linked list, binary tree, graph. It also discusses sorting and searching techniques, file input/output, functions, classes, templates and exercises for students to practice implementing different data structures and algorithms. The instructor's contact details are provided at the beginning.
This document provides an overview of various data structures and algorithms implemented in C++. It begins with introductions to fundamental C++ concepts like classes, inheritance, templates, and pointers. It then covers common linear data structures like linked lists, stacks, and queues. For each, it provides high-level explanations of their properties and implementations using both linked lists and arrays. It also briefly introduces trees, binary trees, binary search trees, and other more advanced topics like graphs and graph algorithms. The document is intended as a set of prelecture notes to introduce key concepts before more in-depth lectures and implementations.
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.
C++ templates allow functions and classes to operate on multiple types of data. Templates define placeholders that are substituted by template arguments. This allows defining functions and classes once that can work with different data types. Function templates define a single function that generates multiple versions based on the template arguments. Class templates generate distinct classes from a single definition. Exceptions represent errors and are thrown using throw statements. Exception handlers use try-catch blocks to catch exceptions and provide error handling.
The document provides information about C++ aptitude and object-oriented programming (OOP) concepts. It contains sample C++ code snippets and questions with explanations to test understanding of topics like classes, inheritance, polymorphism, operator overloading, templates, and more.
C++ How to Program 10th Edition Deitel Solutions Manualleletydanni
C++ How to Program 10th Edition Deitel Solutions Manual
C++ How to Program 10th Edition Deitel Solutions Manual
C++ How to Program 10th Edition Deitel Solutions Manual
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 functions in C++. It begins by showing an example of copying and pasting code to compute 3^4 and 6^5, which is inefficient. It then demonstrates defining a function called raiseToPower() that takes a base and exponent as arguments and computes the power in a reusable way. The document explains the syntax of defining functions, including the return type, arguments, body, and return statement. It also covers topics like function overloading, function prototypes, recursion, and global versus local variables.
The document discusses stacks and their implementation. It introduces stacks and their common operations like push and pop. It describes using stacks to solve problems like reversing a list, calculating in Reverse Polish Notation, and bracket matching by keeping track of opening brackets on a stack. Sample code is provided to implement a stack class with methods like push, pop and top to manipulate items on the stack.
C++ is an object-oriented programming language that is an extension of C. It was developed in the early 1980s by Bjarne Stroustrup at Bell Labs. C++ supports concepts like inheritance, polymorphism, and encapsulation that make it suitable for large, complex programs. Inheritance allows classes to inherit properties from parent classes. Polymorphism is the ability to process objects of different types in the same way. Encapsulation combines data and functions that operate on that data within a single unit, hiding implementation details. File input/output in C++ can be handled through streams like ifstream for input and ofstream for output.
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 5 (20)
This document contains code snippets for 12 common C++ programs: 1) checking if a number is even or odd, 2) swapping two numbers, 3) checking if a year is a leap year, 4) sorting words in dictionary order, 5) calculating a factorial, 6) generating a Fibonacci series, 7) transposing a matrix, 8) using constructors and destructors, 9) demonstrating multiple inheritance, 10) using static members and functions, 11) exception handling, and 12) file input/output. Each code snippet is followed by sample input/output to demonstrate the program's functionality.
Day 1 of the training covers introductory C++ concepts like object-oriented programming, compilers, IDEs, classes, objects, and procedural programming concepts. Day 2 covers more advanced class concepts like constructors, destructors, static members, returning objects, and arrays of objects. Day 3 covers function and operator overloading.
C++ allows for concise summaries in 3 sentences or less:
The document provides an overview of C++ concepts including data types, variables, operators, functions, classes, inheritance and virtual members. It also covers process and thread concepts at a high level. Code examples are provided to illustrate namespaces, input/output, program flow control, overloading, dynamic memory allocation, and classes. The document serves as a brief review of fundamental C++ and system programming concepts.
This document provides an overview of the C++ Data Structures lab manual. It covers topics like C++ review, implementation of various data structures like stack, queue, linked list, binary tree, graph. It also discusses sorting and searching techniques, file input/output, functions, classes, templates and exercises for students to practice implementing different data structures and algorithms. The instructor's contact details are provided at the beginning.
This document provides an overview of various data structures and algorithms implemented in C++. It begins with introductions to fundamental C++ concepts like classes, inheritance, templates, and pointers. It then covers common linear data structures like linked lists, stacks, and queues. For each, it provides high-level explanations of their properties and implementations using both linked lists and arrays. It also briefly introduces trees, binary trees, binary search trees, and other more advanced topics like graphs and graph algorithms. The document is intended as a set of prelecture notes to introduce key concepts before more in-depth lectures and implementations.
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.
C++ templates allow functions and classes to operate on multiple types of data. Templates define placeholders that are substituted by template arguments. This allows defining functions and classes once that can work with different data types. Function templates define a single function that generates multiple versions based on the template arguments. Class templates generate distinct classes from a single definition. Exceptions represent errors and are thrown using throw statements. Exception handlers use try-catch blocks to catch exceptions and provide error handling.
The document provides information about C++ aptitude and object-oriented programming (OOP) concepts. It contains sample C++ code snippets and questions with explanations to test understanding of topics like classes, inheritance, polymorphism, operator overloading, templates, and more.
C++ How to Program 10th Edition Deitel Solutions Manualleletydanni
C++ How to Program 10th Edition Deitel Solutions Manual
C++ How to Program 10th Edition Deitel Solutions Manual
C++ How to Program 10th Edition Deitel Solutions Manual
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 functions in C++. It begins by showing an example of copying and pasting code to compute 3^4 and 6^5, which is inefficient. It then demonstrates defining a function called raiseToPower() that takes a base and exponent as arguments and computes the power in a reusable way. The document explains the syntax of defining functions, including the return type, arguments, body, and return statement. It also covers topics like function overloading, function prototypes, recursion, and global versus local variables.
The document discusses stacks and their implementation. It introduces stacks and their common operations like push and pop. It describes using stacks to solve problems like reversing a list, calculating in Reverse Polish Notation, and bracket matching by keeping track of opening brackets on a stack. Sample code is provided to implement a stack class with methods like push, pop and top to manipulate items on the stack.
C++ is an object-oriented programming language that is an extension of C. It was developed in the early 1980s by Bjarne Stroustrup at Bell Labs. C++ supports concepts like inheritance, polymorphism, and encapsulation that make it suitable for large, complex programs. Inheritance allows classes to inherit properties from parent classes. Polymorphism is the ability to process objects of different types in the same way. Encapsulation combines data and functions that operate on that data within a single unit, hiding implementation details. File input/output in C++ can be handled through streams like ifstream for input and ofstream for output.
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!
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.
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.
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
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Alluxio, Inc.
Alluxio Webinar
June 10, 2025
For more Alluxio Events: https://www.alluxio.io/events/
Speaker:
David Zhu (Engineering Manager @ Alluxio)
Storing data as Parquet files on cloud object storage, such as AWS S3, has become prevalent not only for large-scale data lakes but also as lightweight feature stores for training and inference, or as document stores for Retrieval-Augmented Generation (RAG). However, querying petabyte-to-exabyte-scale data lakes directly from S3 remains notoriously slow, with latencies typically ranging from hundreds of milliseconds to several seconds.
In this webinar, David Zhu, Software Engineering Manager at Alluxio, will present the results of a joint collaboration between Alluxio and a leading SaaS and data infrastructure enterprise that explored leveraging Alluxio as a high-performance caching and acceleration layer atop AWS S3 for ultra-fast querying of Parquet files at PB scale.
David will share:
- How Alluxio delivers sub-millisecond Time-to-First-Byte (TTFB) for Parquet queries, comparable to S3 Express One Zone, without requiring specialized hardware, data format changes, or data migration from your existing data lake.
- The architecture that enables Alluxio’s throughput to scale linearly with cluster size, achieving one million queries per second on a modest 50-node deployment, surpassing S3 Express single-account throughput by 50x without latency degradation.
- Specifics on how Alluxio offloads partial Parquet read operations and reduces overhead, enabling direct, ultra-low-latency point queries in hundreds of microseconds and achieving a 1,000x performance gain over traditional S3 querying methods.
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.
Code and No-Code Journeys: The Coverage OverlookApplitools
Explore practical ways to expand visual and functional UI coverage without deep coding or heavy maintenance in this session. Session recording and more info at applitools.com
How Insurance Policy Administration Streamlines Policy Lifecycle for Agile Op...Insurance Tech Services
A modern Policy Administration System streamlines workflows and integrates with core systems to boost speed, accuracy, and customer satisfaction across the policy lifecycle. Visit https://www.damcogroup.com/insurance/policy-administration-systems for more details!
FME for Climate Data: Turning Big Data into Actionable InsightsSafe Software
Regional and local governments aim to provide essential services for stormwater management systems. However, rapid urbanization and the increasing impacts of climate change are putting growing pressure on these governments to identify stormwater needs and develop effective plans. To address these challenges, GHD developed an FME solution to process over 20 years of rainfall data from rain gauges and USGS radar datasets. This solution extracts, organizes, and analyzes Next Generation Weather Radar (NEXRAD) big data, validates it with other data sources, and produces Intensity Duration Frequency (IDF) curves and future climate projections tailored to local needs. This presentation will showcase how FME can be leveraged to manage big data and prioritize infrastructure investments.
A brief introduction to OpenTelemetry, with a practical example of auto-instrumenting a Java web application with the Grafana stack (Loki, Grafana, Tempo, and Mimir).
Automating Map Production With FME and PythonSafe Software
People still love a good paper map, but every time a request lands on a GIS team’s desk, it takes time to create that perfect, individual map—even when you're ready and have projects prepped. Then come the inevitable changes and iterations that add even more time to the process. This presentation explores a solution for automating map production using FME and Python. FME handles the setup of variables, leveraging GIS reference layers and parameters to manage details like map orientation, label sizes, and layout elements. Python takes over to export PDF maps for each location and template size, uploading them monthly to ArcGIS Online. The result? Fresh, regularly updated maps, ready for anyone to grab anytime—saving you time, effort, and endless revisions while keeping users happy with up-to-date, accessible maps.
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/
Join the Denver Marketo User Group, Captello and Integrate as we dive into the best practices, tools, and strategies for maintaining robust, high-performing databases. From managing vendors and automating orchestrations to enriching data for better insights, this session will unpack the key elements that keep your data ecosystem running smoothly—and smartly.
We will hear from Steve Armenti, Twelfth, and Aaron Karpaty, Captello, and Frannie Danzinger, Integrate.
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!
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/
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.
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
-
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.
4. The this Pointer
– The member functions of every object have
access to a sort of magic pointer named
this, which points to the object itself.
– Thus, any member function can find out
the address of the object of which it is a
member.
5. #include <iostream>
using namespace std;
class where
{
private:
char charray[10]; //occupies 10 bytes
public:
void reveal() {
cout << "nMy object's address is " << this;
}
};
int main()
{
where w1, w2, w3; //make three objects
w1.reveal(); //see where they are
w2.reveal();
w3.reveal();
return 0;
}
Example 1
this Pointer
6. #include <iostream>
using namespace std;
class what {
private:
int alpha;
public:
void tester() {
this->alpha = 11; //same as alpha = 11;
cout << this->alpha; //same as cout << alpha;
}
};
int main() {
what w;
w.tester();
return 0;
}
Example 2
this Pointer
10. Templates and
Exceptions
– Templates make it possible to use one
function or class to handle many different
data types.
– Exceptions provide a convenient, uniform
way to handle errors that occur within
classes.
– The template concept can be used in two
different ways:
▪ with functions
▪ with classes.
11. Function Template Example Scenario
– The following function returns an absolute value for an integer
number:
int abs(int n) {
return (n < 0) ? -n : n;
}
– To calculate the absolute value for each different data type requires
rewriting the same function for each data type.
– The solution for this problem is the function template.
14. #include <iostream>
using namespace std;
//function returns index number of item, or -1 if not found
template <class atype>
int find(atype *array, atype value, int size)
{
for (int j = 0; j < size; j++)
if (array[j] == value)
return j;
return -1;
}
char chrArr[] = { 1, 3, 5, 9, 11, 13 }; //array
char ch = 5; //value to find
int intArr[] = { 1, 3, 5, 9, 11, 13 };
int in = 6;
long lonArr[] = { 1L, 3L, 5L, 9L, 11L, 13L };
long lo = 11L;
double dubArr[] = { 1.0, 3.0, 5.0, 9.0, 11.0, 13.0 };
double db = 4.0;
int main()
{
cout << "n 5 in chrArray, index = " << find(chrArr, ch, 6);
cout << "n 6 in intArray, index = " << find(intArr, in, 6);
cout << "n11 in lonArray, index = " << find(lonArr, lo, 6);
cout << "n 4 in dubArray, index = " << find(dubArr, db, 6);
return 0;
}
Example 2
Function Template
15. #include <iostream>
using namespace std;
const int MAX = 100; //size of array
template <class Type>
class Stack
{
private:
Type st[MAX]; //stack: array of any type
int top; //number of top of stack
public:
Stack() //constructor
{
top = -1;
}
void push(Type var) //put number on stack
{
st[++top] = var;
}
Type pop() //take number off stack
{
return st[top--];
}
};
int main()
{
Stack<float> s1; //s1 is object of class Stack<float>
s1.push(1111.1F); //push 3 floats, pop 3 floats
s1.push(2222.2F);
s1.push(3333.3F);
cout << "1: " << s1.pop() << endl;
cout << "2: " << s1.pop() << endl;
cout << "3: " << s1.pop() << endl;
Stack<long> s2; //s2 is object of class Stack<long>
s2.push(123123123L); //push 3 longs, pop 3 longs
s2.push(234234234L);
s2.push(345345345L);
cout << "1: " << s2.pop() << endl;
cout << "2: " << s2.pop() << endl;
cout << "3: " << s2.pop() << endl;
return 0;
}
Example 3
Function Template
16. #include <iostream>
using namespace std;
const int LEN = 80; //maximum length of names
class employee //employee class
{
private:
char name[LEN]; //employee name
unsigned long number; //employee number
public:
friend istream & operator >> (istream &s, employee &e);
friend ostream & operator << (ostream &s, employee &e);
};
istream & operator >> (istream &s, employee &e)
{
cout << "n Enter last name: ";
cin >> e.name;
cout << " Enter number: ";
cin >> e.number;
return s;
}
ostream & operator << (ostream &s, employee &e)
{
cout << "n Name : " << e.name;
cout << "n Number : " << e.number;
return s;
}
template<class TYPE> //struct "link<TYPE>"
struct link //one element of list
{
TYPE data; //data item
link* next; //pointer to next link
};
template<class TYPE> //class "linklist<TYPE>"
class linklist //a list of links
{
private:
link<TYPE> *first; //pointer to first link
public:
linklist() //no-argument constructor
{
first = NULL; //no first link
}
void additem(TYPE d); //add data item (one link)
void display(); //display all links
};
template<class TYPE>
void linklist<TYPE>::additem(TYPE d) //add data item
{
link<TYPE> *newlink = new link<TYPE>; //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
}
template<class TYPE>
void linklist<TYPE>::display() //display all links
{
link<TYPE> *current = first; //set ptr to first link
while (current != NULL) //quit on last link
{
cout << endl << current->data; //display data
current = current->next; //move to next link
}
}
int main()
{ //lemp is object of
linklist<employee> lemp; //class "linklist<employee>”
employee emptemp; //temporary employee storage
char ans; //user's response
do
{
cin >> emptemp; //get employee data from user
lemp.additem(emptemp); //add it to linked list ‘lemp’
cout << "nAdd another (y/n)? ";
cin >> ans;
} while (ans != 'n'); //when user is done,
lemp.display(); //display entire linked list
return 0;
}
Linked List Class
Using
Templates
Example
18. Exceptions
– Exception are used to handle errors in the objects.
– Consider a member function detects an error, and then informs the application that an
error has occurred.
– This is called throwing an exception.
– In the application, a separate section of code to is installed to handle
the error.
– This code is called an exception handler or catch block; it catches the exceptions thrown by
the member function.
– Any code in the application that uses objects of the class is enclosed in
a try block.
– Errors generated in the try block will be caught in the catch block.
20. #include <iostream>
#include <stdexcept>
using namespace std;
int main() {
try {
int numerator, denominator;
cout << "Enter numerator: ";
cin >> numerator;
cout << "Enter denominator: ";
cin >> denominator;
if (denominator == 0) {
throw runtime_error("Division by zero is not allowed.");
}
double result = static_cast<double>(numerator) / denominator;
cout << "Result: " << result << endl;
}
catch (const exception &ex) {
cerr << "An exception occurred: " << ex.what() << endl;
}
return 0;
}
Example 1
Basic Example
21. #include <iostream>
using namespace std;
const int MAX = 3; //stack holds 3 integers
class Stack
{
private:
int st[MAX]; //stack: array of integers
int top; //index of top of stack
public:
class Full { }; //exception class
class Empty { }; //exception class
Stack() : top(-1)
{ }
void push(int var) //put number on stack
{
if (top >= MAX - 1) //if stack full,
throw Full(); //throw Full exception
st[++top] = var;
}
int pop() //take number off stack
{
if (top < 0) //if stack empty,
throw Empty(); //throw Empty exception
return st[top--];
}
};
int main()
{
Stack s1;
try {
s1.push(11);
s1.push(22);
s1.push(33);
// s1.push(44); //oops: stack full
cout << "1: " << s1.pop() << endl;
cout << "2: " << s1.pop() << endl;
cout << "3: " << s1.pop() << endl;
// cout << "4: " << s1.pop() << endl; //oops: stack empty
}
catch (Stack::Full) {
cout << "Exception: Stack Full" << endl;
}
catch (Stack::Empty) {
cout << "Exception: Stack Empty" << endl;
}
return 0;
}
Example 2
Exceptions
22. #include <iostream>
using namespace std;
class Distance //English Distance class
{
private:
int feet;
float inches;
public:
class InchesEx { }; //exception class
Distance() : feet(0), inches(0.0)
{ }
Distance(int ft, float in) //constructor (two args)
{
if (in >= 12.0) //if inches too big,
throw InchesEx(); //throw exception
feet = ft;
inches = in;
}
void getdist() //get length from user
{
cout << "nEnter feet : ";
cin >> feet;
cout << "Enter inches : ";
cin >> inches;
if (inches >= 12.0) //if inches too big,
throw InchesEx(); //throw exception
}
void showdist() {
cout << feet << "' - " << inches << '“’;
}
};
int main()
{
try {
Distance dist1(17, 3.5); //2-arg constructor
Distance dist2; //no-arg constructor
dist2.getdist(); //get distance from user
//display distances
cout << "ndist1 = ";
dist1.showdist();
cout << "ndist2 = ";
dist2.showdist();
}
catch (Distance::InchesEx) {
cout << "nInitialization error: inches value is too large.";
}
return 0;
}
Example 3
Exceptions
23. #include <iostream>
#include <string>
using namespace std;
class Distance
{
private:
int feet;
float inches;
public:
class InchesEx //exception class
{
public:
string origin; //for name of routine
float iValue; //for faulty inches value
InchesEx(string orig, float inch) //2-arg constructor
{
origin = orig; //store string
iValue = inch; //store inches
}
};
Distance() : feet(0), inches(0.0)
{ }
Distance(int ft, float in)
{
if (in >= 12.0)
throw InchesEx("2-arg constructor", in);
feet = ft;
inches = in;
}
void getdist() //get length from user
{
cout << "nEnter feet: ";
cin >> feet;
cout << "Enter inches: ";
cin >> inches;
if (inches >= 12.0)
throw InchesEx("getdist() function", inches);
}
void showdist() //display distance
{
cout << feet << "' - " << inches << '“’;
}
};
int main()
{
try {
Distance dist1(17, 3.5); //2-arg constructor
Distance dist2; //no-arg constructor
dist2.getdist(); //get value
//display distances
cout << "ndist1 = ";
dist1.showdist();
cout << "ndist2 = ";
dist2.showdist();
}
catch (Distance::InchesEx ix) {
cout << "Initialization error in " << ix.origin << endl;
cout << "Inches value of " << ix.iValue << " is too large.";
}
return 0;
}
Example 4
Exceptions origin and
value