This document discusses object-oriented programming concepts in C++ including objects as function parameters and return types, friend classes and functions. It provides examples of passing an object as a parameter to a function, returning an object from a function, and declaring friend classes and functions to access private members. The examples demonstrate how to add values of object data members when an object is passed as a parameter or returned.
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.
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.
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.
Classes and objects are fundamental concepts in object-oriented programming. A class defines the data and functions that characterize objects of a certain kind, acting as a blueprint. An object is an instance of a class, which reserves and allocates memory at runtime. Classes use access specifiers like public and private to determine whether data members and methods can be accessed within or outside the class. Objects are declared as instances of a class and can access class members using the dot operator. Member functions allow manipulating object data.
The document discusses object-oriented programming concepts like classes, objects, member functions, data members, constructors, and encapsulation. It explains that a class defines the structure and behavior of objects, with data members representing attributes and member functions representing behaviors. Constructors initialize an object's data when it is created. Encapsulation protects data by making it private and only accessible through public member functions.
C++ppt. Classs and object, class and objectsecondakay
油
1. Classes are blueprints that define objects with attributes (data members) and behaviors (member functions). Objects are instantiated from classes.
2. The Time class implements a time abstract data type with data members for hours, minutes, seconds and member functions to set time and print time in different formats.
3. Classes allow for encapsulation of data and functions, information hiding of implementation details, and software reusability through class libraries.
This document provides information about a lecture on polymorphism for the Object Oriented Programming course at MVPSs KBT College of Engineering. It lists the name of the faculty member, department, college, subject name, teaching scheme, examination scheme, textbooks, reference books, e-books, video lectures, and topics to be covered in the unit on polymorphism along with number of hours for each topic.
The document provides information about object-oriented programming concepts in C++ including class, object, constructor, destructor, access specifiers, data members, member functions, static members, and friend functions. It defines each concept, provides syntax examples, and explains how to create a class, make objects, and access members. Constructors are used to initialize objects while destructors deallocate memory. Access specifiers determine public, private, and protected access.
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.
Friend functions and classes allow external code to access private members of a class. The document demonstrates declaring a function and class as friends of the Rectangle class to access its private length and width variables. This is done by specifying the function or class as friend within the class definition. This allows the friend function getCost() and class CostCalculator to multiply length and width to calculate the area or cost despite them being private members.
This document provides an overview of object-oriented programming (OOP) concepts in C++ including objects, classes, abstraction, encapsulation, inheritance, and polymorphism. It defines each concept, provides examples in C++ code, and explains how they allow code reuse and flexibility through bundling of data and functions into objects that can be specialized into different forms. The document is intended to introduce the core OOP principles in C++ for educational purposes as part of a mentoring program.
This document discusses object-oriented programming concepts in C++ including polymorphism, virtual functions, pure virtual functions, and abstract classes. It covers topics such as function overloading, operator overloading, virtual base classes, virtual functions, and pure virtual functions. It provides examples of overloading unary and binary operators using member functions and friend functions. It also explains the differences between virtual functions and pure virtual functions, and how abstract classes are used with pure virtual functions.
The document discusses classes and objects in object-oriented programming. It defines what a class is, how classes are declared with public and private members, and how objects are instantiated from classes. It also describes defining member functions inside and outside of classes, and the use of static class members and friend functions.
The document outlines a lecture plan for object oriented programming. It covers topics like structures and classes, function overloading, constructors and destructors, operator overloading, inheritance, polymorphism, and file streams. It provides examples to explain concepts like structures, classes, access specifiers, friend functions, and operator overloading. The document also includes questions for students to practice these concepts.
Here is a C++ program that implements a Polynomial class with overloaded operators as specified in the question:
#include <iostream>
using namespace std;
class Term {
public:
int coefficient;
int exponent;
Term(int coeff, int exp) {
coefficient = coeff;
exponent = exp;
}
};
class Polynomial {
public:
Term* terms;
int numTerms;
Polynomial() {
terms = NULL;
numTerms = 0;
}
Polynomial(Term t[]) {
terms = t;
numTerms = sizeof(t)/sizeof(t[0]);
}
~Polynomial() {
delete[] terms;
}
Polynomial
The document outlines the course content for a C++ introductory course, including introductions to OOP concepts like classes and objects, pointers, functions, inheritance, and polymorphism. It also covers basic C++ programming concepts like I/O, data types, operators, and data structures. The course aims to provide students with fundamental C++ programming skills through explanations and examples of key C++ features.
This is the object oriented lecture nmbr 3rd , if you want lecture 2 or 1 u can check it my account , this is the programing tutorial, please follow me and thank you
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
Classes and objects allow programmers to create user-defined data types in C++. A class specifies the data and functions that operate on that data. Objects are instances of a class that allocate memory for the data members. Classes support key object-oriented concepts like data hiding, inheritance, and treating user-defined types like built-in types through objects. Member functions defined inside or outside the class can access private data members while non-member functions cannot unless declared as friends.
2nd puc computer science chapter 8 function overloading ,types of function overloading ,syntax function overloading ,example function overloading
inline function, friend function ,
The document discusses various C++ concepts including static class members, the this pointer, friend functions and classes, dynamic memory management using new and delete operators, function overloading, operator overloading, templates, and inheritance. Static class members are accessible to all objects of the class and only one copy is created for the entire class. The this pointer refers to the current object from within non-static member functions. Friend functions and classes can access private members of other classes. Dynamic memory is allocated using new and freed using delete.
This document discusses function overloading, inline functions, and friend functions in C++. It defines function overloading as having two or more functions with the same name but different parameters. Inline functions have their body inserted at the call site instead of transferring control. Friend functions are non-member functions that have access to private members of a class. Examples are provided for each concept. The advantages of inline functions are reduced code size and faster execution, while disadvantages include increased file size and memory usage.
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 defining programmer-defined classes in Java. It provides examples of defining a Bicycle class with data members and methods, creating multiple Bicycle objects, and using the Bicycle class in another class. It also covers concepts like visibility modifiers, constants, local variables, and passing objects to methods.
The document discusses defining programmer-defined classes in Java. It provides an example of defining a Bicycle class with data members and methods, and using it to track bicycle ownership. It then expands on this example by defining an Account class and using both classes in a sample program. The key aspects covered include defining classes, using visibility modifiers, passing objects to methods, and differentiating local variables from data members and parameters.
The document discusses goal setting and defines goals as the end toward which effort is directed. It distinguishes between long-term and short-term goals and notes that goals require action, unlike dreams. The document outlines characteristics of effective goals, noting they should be specific, measurable, action-oriented, realistic, and time-bound. Common obstacles to goal achievement like lack of commitment or support are also discussed. Finally, the document provides tips for staying motivated and overcoming failure, like treating yourself well and keeping track of accomplishments.
Inheritance allows one class to inherit properties and behaviors from another parent class. This creates a hierarchical relationship between classes and allows code reuse. There are three types of access specifiers that determine whether inherited members from the parent class are public, private, or protected in the child class. Virtual functions allow runtime polymorphism by overriding functions in derived classes. Pure virtual functions define an interface for derived classes by requiring them to implement the function.
More Related Content
Similar to Lec_15_OOP_ObjectsAsParametersFriendClasses.pdf (20)
The document provides information about object-oriented programming concepts in C++ including class, object, constructor, destructor, access specifiers, data members, member functions, static members, and friend functions. It defines each concept, provides syntax examples, and explains how to create a class, make objects, and access members. Constructors are used to initialize objects while destructors deallocate memory. Access specifiers determine public, private, and protected access.
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.
Friend functions and classes allow external code to access private members of a class. The document demonstrates declaring a function and class as friends of the Rectangle class to access its private length and width variables. This is done by specifying the function or class as friend within the class definition. This allows the friend function getCost() and class CostCalculator to multiply length and width to calculate the area or cost despite them being private members.
This document provides an overview of object-oriented programming (OOP) concepts in C++ including objects, classes, abstraction, encapsulation, inheritance, and polymorphism. It defines each concept, provides examples in C++ code, and explains how they allow code reuse and flexibility through bundling of data and functions into objects that can be specialized into different forms. The document is intended to introduce the core OOP principles in C++ for educational purposes as part of a mentoring program.
This document discusses object-oriented programming concepts in C++ including polymorphism, virtual functions, pure virtual functions, and abstract classes. It covers topics such as function overloading, operator overloading, virtual base classes, virtual functions, and pure virtual functions. It provides examples of overloading unary and binary operators using member functions and friend functions. It also explains the differences between virtual functions and pure virtual functions, and how abstract classes are used with pure virtual functions.
The document discusses classes and objects in object-oriented programming. It defines what a class is, how classes are declared with public and private members, and how objects are instantiated from classes. It also describes defining member functions inside and outside of classes, and the use of static class members and friend functions.
The document outlines a lecture plan for object oriented programming. It covers topics like structures and classes, function overloading, constructors and destructors, operator overloading, inheritance, polymorphism, and file streams. It provides examples to explain concepts like structures, classes, access specifiers, friend functions, and operator overloading. The document also includes questions for students to practice these concepts.
Here is a C++ program that implements a Polynomial class with overloaded operators as specified in the question:
#include <iostream>
using namespace std;
class Term {
public:
int coefficient;
int exponent;
Term(int coeff, int exp) {
coefficient = coeff;
exponent = exp;
}
};
class Polynomial {
public:
Term* terms;
int numTerms;
Polynomial() {
terms = NULL;
numTerms = 0;
}
Polynomial(Term t[]) {
terms = t;
numTerms = sizeof(t)/sizeof(t[0]);
}
~Polynomial() {
delete[] terms;
}
Polynomial
The document outlines the course content for a C++ introductory course, including introductions to OOP concepts like classes and objects, pointers, functions, inheritance, and polymorphism. It also covers basic C++ programming concepts like I/O, data types, operators, and data structures. The course aims to provide students with fundamental C++ programming skills through explanations and examples of key C++ features.
This is the object oriented lecture nmbr 3rd , if you want lecture 2 or 1 u can check it my account , this is the programing tutorial, please follow me and thank you
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
Classes and objects allow programmers to create user-defined data types in C++. A class specifies the data and functions that operate on that data. Objects are instances of a class that allocate memory for the data members. Classes support key object-oriented concepts like data hiding, inheritance, and treating user-defined types like built-in types through objects. Member functions defined inside or outside the class can access private data members while non-member functions cannot unless declared as friends.
2nd puc computer science chapter 8 function overloading ,types of function overloading ,syntax function overloading ,example function overloading
inline function, friend function ,
The document discusses various C++ concepts including static class members, the this pointer, friend functions and classes, dynamic memory management using new and delete operators, function overloading, operator overloading, templates, and inheritance. Static class members are accessible to all objects of the class and only one copy is created for the entire class. The this pointer refers to the current object from within non-static member functions. Friend functions and classes can access private members of other classes. Dynamic memory is allocated using new and freed using delete.
This document discusses function overloading, inline functions, and friend functions in C++. It defines function overloading as having two or more functions with the same name but different parameters. Inline functions have their body inserted at the call site instead of transferring control. Friend functions are non-member functions that have access to private members of a class. Examples are provided for each concept. The advantages of inline functions are reduced code size and faster execution, while disadvantages include increased file size and memory usage.
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 defining programmer-defined classes in Java. It provides examples of defining a Bicycle class with data members and methods, creating multiple Bicycle objects, and using the Bicycle class in another class. It also covers concepts like visibility modifiers, constants, local variables, and passing objects to methods.
The document discusses defining programmer-defined classes in Java. It provides an example of defining a Bicycle class with data members and methods, and using it to track bicycle ownership. It then expands on this example by defining an Account class and using both classes in a sample program. The key aspects covered include defining classes, using visibility modifiers, passing objects to methods, and differentiating local variables from data members and parameters.
The document discusses goal setting and defines goals as the end toward which effort is directed. It distinguishes between long-term and short-term goals and notes that goals require action, unlike dreams. The document outlines characteristics of effective goals, noting they should be specific, measurable, action-oriented, realistic, and time-bound. Common obstacles to goal achievement like lack of commitment or support are also discussed. Finally, the document provides tips for staying motivated and overcoming failure, like treating yourself well and keeping track of accomplishments.
Inheritance allows one class to inherit properties and behaviors from another parent class. This creates a hierarchical relationship between classes and allows code reuse. There are three types of access specifiers that determine whether inherited members from the parent class are public, private, or protected in the child class. Virtual functions allow runtime polymorphism by overriding functions in derived classes. Pure virtual functions define an interface for derived classes by requiring them to implement the function.
This document discusses static data members in C++. It explains that a static data member is shared among all objects of a class and is defined with the static keyword. Only one variable is created in memory even if there are multiple class objects. It is visible only within the class and persists for the lifetime of the program. The document provides examples of declaring and defining static data members separately, and using a static member to assign unique roll numbers to student objects.
- RANSAC (RANdom SAmple Consensus) is an algorithm used to estimate parameters of a mathematical model from a set of observed data that contains outliers.
- It works by randomly selecting a minimum set of data points required to estimate the model parameters, estimating the model, then determining how many total data points the model fits within a threshold.
- It repeats this process numerous times, and the model with the highest number of fitting data points is selected. This helps identify the correct model from outliers in the data.
This document summarizes a lecture on image transformations and warping. It discusses:
1) Different types of geometric transformations between images like similarity transformations involving translation, rotation and scaling.
2) Image warping which changes the domain of an image by applying a transformation to its coordinates, as opposed to filtering which changes the range/values.
3) Parametric or global warping which applies the same transformation to all points using parameters, and linear transformations represented by 2x2 matrices including translations, rotations, scaling and shears.
4) Homographies or projective transformations which include affine transformations and projective warps, mapping lines to lines but not preserving parallelism or ratios.
This document summarizes two studies on gait analysis conducted by Anees Qumar Abbasi from the Institute of Biomedical Engineering. The first study analyzed the stride interval of the left and right feet together under normal and diseased conditions. The second study used normalized corrected Shannon entropy to quantify the effects of aging and disease on gait. The results showed NCSE could distinguish between older Parkinson's patients and young, and young Parkinson's and healthy controls. P-values from classifications between groups were also provided.
This document discusses key elements needed to build a perfect school system. It begins with an agenda outlining topics like defining a best model school, vision/mission, challenges, and best practices. It states the model school should provide all students with a high-quality education tailored to their needs. Several elements are identified as important, including modern facilities, high-quality teachers, and a curriculum addressing individual student needs/interests. The document then explores topics like the importance of education, developing a vision/mission, ensuring a strong curriculum, innovative teaching methods, and hiring quality teachers.
1. Inheritance allows a derived class to inherit characteristics from a base class while also adding its own unique characteristics.
2. Generalization involves extracting common characteristics from classes into a new base class that the original classes inherit from.
3. Subtyping (extension) means the derived class is behaviorally compatible with the base class, while specialization (restriction) means the derived class is behaviorally incompatible.
This document outlines the course details for an Object Oriented Programming course taught by Dr. Anees Qumar Abbasi. The course aims to teach object-oriented concepts, analysis, and software development using C++. It will cover key OOP principles like abstraction, encapsulation, polymorphism, and inheritance. The course outline includes topics like classes and objects, inheritance and polymorphism, encapsulation and abstraction, and exception handling. Students will learn through slides, notes, and reference books, and can contact the instructor by email or Piazza for any questions.
This document provides information about the Computer Vision course CSE/ECE 576 taught by Professor Linda Shapiro at the University of Washington. The course meets on Mondays and Wednesdays from 1:30-2:50pm in room ECE 037. It covers topics in low, mid, and high-level computer vision through six programming assignments and a final course project. The assignments involve building a computer vision library from the ground up in C and experimenting with tools like neural networks. The document outlines the grading breakdown and lists additional resources.
How to Configure Flexible Working Schedule in Odoo 18 EmployeeCeline George
油
In this slide, well discuss on how to configure flexible working schedule in Odoo 18 Employee module. In Odoo 18, the Employee module offers powerful tools to configure and manage flexible working schedules tailored to your organization's needs.
Blind spots in AI and Formulation Science, IFPAC 2025.pdfAjaz Hussain
油
The intersection of AI and pharmaceutical formulation science highlights significant blind spotssystemic gaps in pharmaceutical development, regulatory oversight, quality assurance, and the ethical use of AIthat could jeopardize patient safety and undermine public trust. To move forward effectively, we must address these normalized blind spots, which may arise from outdated assumptions, errors, gaps in previous knowledge, and biases in language or regulatory inertia. This is essential to ensure that AI and formulation science are developed as tools for patient-centered and ethical healthcare.
Useful environment methods in Odoo 18 - Odoo 際際滷sCeline George
油
In this slide well discuss on the useful environment methods in Odoo 18. In Odoo 18, environment methods play a crucial role in simplifying model interactions and enhancing data processing within the ORM framework.
Prelims of Kaun TALHA : a Travel, Architecture, Lifestyle, Heritage and Activism quiz, organized by Conquiztadors, the Quiz society of Sri Venkateswara College under their annual quizzing fest El Dorado 2025.
Information Technology for class X CBSE skill SubjectVEENAKSHI PATHAK
油
These questions are based on cbse booklet for 10th class information technology subject code 402. these questions are sufficient for exam for first lesion. This subject give benefit to students and good marks. if any student weak in one main subject it can replace with these marks.
Mate, a short story by Kate Grenvile.pptxLiny Jenifer
油
A powerpoint presentation on the short story Mate by Kate Greenville. This presentation provides information on Kate Greenville, a character list, plot summary and critical analysis of the short story.
Finals of Rass MELAI : a Music, Entertainment, Literature, Arts and Internet Culture Quiz organized by Conquiztadors, the Quiz society of Sri Venkateswara College under their annual quizzing fest El Dorado 2025.
How to Configure Restaurants in Odoo 17 Point of SaleCeline George
油
Odoo, a versatile and integrated business management software, excels with its robust Point of Sale (POS) module. This guide delves into the intricacies of configuring restaurants in Odoo 17 POS, unlocking numerous possibilities for streamlined operations and enhanced customer experiences.
APM event hosted by the South Wales and West of England Network (SWWE Network)
Speaker: Aalok Sonawala
The SWWE Regional Network were very pleased to welcome Aalok Sonawala, Head of PMO, National Programmes, Rider Levett Bucknall on 26 February, to BAWA for our first face to face event of 2025. Aalok is a member of APMs Thames Valley Regional Network and also speaks to members of APMs PMO Interest Network, which aims to facilitate collaboration and learning, offer unbiased advice and guidance.
Tonight, Aalok planned to discuss the importance of a PMO within project-based organisations, the different types of PMO and their key elements, PMO governance and centres of excellence.
PMOs within an organisation can be centralised, hub and spoke with a central PMO with satellite PMOs globally, or embedded within projects. The appropriate structure will be determined by the specific business needs of the organisation. The PMO sits above PM delivery and the supply chain delivery teams.
For further information about the event please click here.
Finals of Kaun TALHA : a Travel, Architecture, Lifestyle, Heritage and Activism quiz, organized by Conquiztadors, the Quiz society of Sri Venkateswara College under their annual quizzing fest El Dorado 2025.
SOCIAL CHANGE(a change in the institutional and normative structure of societ...DrNidhiAgarwal
油
This PPT is showing the effect of social changes in human life and it is very understandable to the students with easy language.in this contents are Itroduction, definition,Factors affecting social changes ,Main technological factors, Social change and stress , what is eustress and how social changes give impact of the human's life.
The basics of sentences session 6pptx.pptxheathfieldcps1
油
Lec_15_OOP_ObjectsAsParametersFriendClasses.pdf
1. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Women University of Azad Jammu and Kashmir Bagh
Department of Computer Sciences and Information Technology, Women University of Azad Jammu and Kashmir Bagh
www.wuajk.edu.pk
Object Oriented Programming
CS-3201
Dr. Anees Qumar Abbasi
aneesabbasi.wuajk@gmail.com
2. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Objects as Function Parameters
& Return Type
Friend Classes & Functions
3. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Object as Function Parameters
Objects can also be passed as parameters to member functions.
The method of passing objects to a functions as parameters is as
passing other simple variables.
It will easily be understand by following example.
4. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Example: Object as Parameter
void add(Travel p)
{
Travel t;
t.km=km+p.km;
t.hr=hr+p.hr;
cout<<Total traveling
is <<t.km<< kilometers
in
<<t.hr<< hours<<endl;
}
};
void main()
{
Travel my, your;
my.get();
my.show();
your.get();
your.show();
my.add(your);
getch();
}
class Travel
{
private:
int km, hr;
public:
Travel()
{
km=hr=0;
}
void get()
{
cout<<Enter Kilometers
traveled;cin>>km;
cout<<Enter Hours
traveled;cin>>hr;
}
void show() {
cout<<You traveled
<<km<< in <<hr<<
hours<<endl;
}
5. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
How Program Works
void add(Travel p) {
Travel t;
t.km = km + p.km;
t.hr = hr + p.hr;
}
Data members of temporary object t
Data members of temporary object my
Data members of temporary object p
The above program declares to objects of class Travel and inputs data in both objects.
The add() function accepts an object of type Travel as parameter.
It adds the values of data members of the parameter object and the values of calling objects data members
and displays the result.
The working of member function add() is as follows:
Function call in main
my.add(your);
6. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Returning Objects from Member Function
The method of returning an object from member function is same as
returning a simple variable.
If a member function returns an object, its return type should be the
same as the type of object to be returned.
7. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Example: Object as Parameter
Travel add(Travel p)
{
Travel t;
t.km=km+p.km;
t.hr=hr+p.hr;
return t;
}
};
void main()
{
Travel my, your, r;
my.get();
my.show();
your.get();
your.show();
r = my.add(your);
cout<<Total travelling is as
follow:n;
r.show();
getch();
}
class Travel
{
private:
int km, hr;
public:
Travel()
{
km=hr=0;
}
void get()
{
cout<<Enter Kilometers
traveled;cin>>km;
cout<<Enter Hours
traveled;cin>>hr;
}
void show() {
Cout<<You traveled
<<km<< in <<hr<<
hours<<endl;
}
8. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
The add() function in the above program accepts a parameter object
of type Travel.
It adds the contents of parameter and calling object and stores the
result in a temporary object.
The function then returns the whole object back to main() function
that is stored in r.
The program finally displays the result using r.show() statement.
How Program Works
9. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Friend Classes
A friend class can access private and protected members of other classes in
which it is declared as a friend. It is sometimes useful to allow a particular
class to access private and protected members of other classes.
We can declare a friend class in C++ by using the friend keyword.
friend class class_name; // declared in the base class
10. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Example: Friend Class
class GFG {
private:
int private_variable;
protected:
int protected_variable;
public:
GFG()
{
private_variable = 10;
protected_variable = 99;
}
// friend class declaration
friend class F;
};
// Here, class F is declared as a
friend inside class GFG. Therefore,
F is a friend of class GFG. Class F
can access the private members of
class GFG.
class F {
public:
void display(GFG& t)
{
cout << "The value of Private Variable
= "<< t.private_variable << endl;
cout << "The value of Protected
Variable = "<< t.protected_variable;
}
};
// Driver code
int main()
{
GFG g;
F fri;
fri.display(g);
return 0;
} Output:
The value of Private Variable = 10
The value of Protected Variable = 99
11. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Friend Function
Like a friend class, a friend function can be granted special access to private and
protected members of a class in C++. They are the non-member functions that can
access and manipulate the private and protected members of the class for they are
declared as friends.
A friend function can be:
1. A global function
2. A member function of another class
12. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Friend Function
Syntax:
friend return_type function_name (arguments); // for a global function
or friend return_type
class_name::function_name (arguments);// for a member function of other class
13. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Example: Friend Function
1. Global Function as Friend Function
class base {
private:
int private_variable;
protected:
int protected_variable;
public:
base()
{
private_variable = 10;
protected_variable = 99;
}
// friend function declaration
friend void friendFunction(base&
obj);
};
// friend function definition
void friendFunction(base& obj)
{
cout << "Private Variable:" <<
obj.private_variable<< endl;
cout << "Protected Variable:" <<
obj.protected_variable;
}
int main()
{
base object1;
friendFunction(object1);
return 0;
}
Output:
Private Variable: 10
Protected Variable: 99
14. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Example: Friend Function
2. Member Function of Another Class a Friend Function
class anotherClass {
public:
void memberFunction();
};
// base class for which friend is
declared
class base {
private:
int private_variable;
protected:
int protected_variable;
public:
base()
{ private_variable = 10;
protected_variable = 99; }
// friend function declaration
friend void
anotherClass::memberFunction();
};
// friend function definition
void anotherClass::memberFunction(base&
obj)
{
cout << "Private Variable: " <<
obj.private_variable<< endl;
cout << "Protected Variable: " <<
obj.protected_variable;
}
Void main()
{
base object1;
anotherClass object2;
object2.memberFunction(object1);
}
Output:
Private Variable: 10
Protected Variable: 99
15. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Features of Friend Functions
q A friend function is a special function in C++ that in spite of not being a member
function of a class has the privilege to access the private and protected data of a
class.
q A friend function is a non-member function or ordinary function of a class, which is
declared as a friend using the keyword friend inside the class. By declaring a
function as a friend, all the access permissions are given to the function.
q The keyword friend is placed only in the function declaration of the friend function
and not in the function definition or call.
q A friend function is called like an ordinary function. It cannot be called using the
object name and dot operator. However, it may accept the object as an argument
whose value it wants to access.
q A friend function can be declared in any section of the class i.e. public or private or
protected.
16. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Friend Functions
Advantages of Friend Functions
A friend function is able to access members without the need of inheriting the
class.
The friend function acts as a bridge between two classes by accessing their
private data.
It can be used to increase the versatility of overloaded operators.
It can be declared either in the public or private or protected part of the class.
Disadvantages of Friend Functions
Friend functions have access to private members of a class from outside the class
which violates the law of data hiding.
Friend functions cannot do any run-time polymorphism in their members.
17. Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Friend Functions & Classes
v Friends should be used only for limited purposes. Too many functions or external
classes are declared as friends of a class with protected or private data access
lessens the value of encapsulation of separate classes in object-oriented
programming.
v Friendship is not mutual. If class A is a friend of B, then B doesnt become a friend of
A automatically.
v Friendship is not inherited.
v The concept of friends is not in Java.