The document discusses friend functions and classes. Friend functions and classes allow functions or classes access to private data of other classes. A friend function has access to all private members of the class for which it is a friend. To declare a friend function, its prototype is included within the class preceded by the keyword 'friend'. Friend functions bypass C++'s data hiding principle and allow access to private data, so they should be used with caution. The document provides examples of declaring friend functions and using them to access private class data.
1. The document describes a midterm exam for a C++ programming course that consists of multiple choice questions and has a time limit of 2 hours.
2. It provides sample exam questions about C++ concepts like functions, variables, conditionals, and data types.
3. The student completed the exam, scoring 64 out of 100 points within the 2 hour time limit.
The document discusses parallel computing and multi-core CPUs. It presents an example of manually parallelizing a matrix multiplication algorithm using threads. It then shows how the Parallel Extensions in .NET simplify this by using Parallel.For. The document also discusses specification languages like Spec# that allow pre- and post-conditions to be specified, catching errors earlier.
C++ classes allow programmers to encapsulate data and functions into user-defined types called classes. A class defines the data attributes and functions that operate on those attributes. Classes support object-oriented programming by allowing objects to be created from a class which store and manipulate data private to the class through public member functions.
Object Oriented Programming involves modeling real-world entities as objects that encapsulate both data and behavior. Classes define these objects by grouping related data members and functions together, and objects are instantiated from classes. Some key aspects of OOP include:
1. Encapsulation which involves hiding implementation details within classes and exposing a public interface.
2. Inheritance which allows a derived class to extend a base class while retaining shared properties.
3. Dynamic binding which enables polymorphic behavior where derived classes can exhibit different behavior than base classes in the same context.
Object Oriented Programming involves modeling real-world entities as objects that encapsulate both data and behavior. Classes define these objects by grouping the data (attributes) and functions (methods) that operate on that data. In C++, classes use access specifiers like public and private to control whether data and methods can be accessed from outside the class or only within the class. Methods are defined either inside or outside the class using the scope resolution operator. Objects are instantiated from classes and their methods and data can be accessed using dot or arrow operators.
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.
The document discusses object-oriented programming concepts in C#, including classes, constructors, destructors, and access modifiers. It provides examples of how to define classes with properties, methods, and constructors. It also explains the differences between public, private, and protected access modifiers and how they control accessibility of class members both within and outside of a class. The document contains code examples demonstrating the usage of classes, constructors, and access modifiers in C#.
1. The document describes a midterm exam for a C++ programming course that consists of multiple choice questions and has a time limit of 2 hours.
2. It provides sample exam questions about C++ concepts like functions, variables, conditionals, and data types.
3. The student completed the exam, scoring 64 out of 100 points within the 2 hour time limit.
The document discusses parallel computing and multi-core CPUs. It presents an example of manually parallelizing a matrix multiplication algorithm using threads. It then shows how the Parallel Extensions in .NET simplify this by using Parallel.For. The document also discusses specification languages like Spec# that allow pre- and post-conditions to be specified, catching errors earlier.
C++ classes allow programmers to encapsulate data and functions into user-defined types called classes. A class defines the data attributes and functions that operate on those attributes. Classes support object-oriented programming by allowing objects to be created from a class which store and manipulate data private to the class through public member functions.
Object Oriented Programming involves modeling real-world entities as objects that encapsulate both data and behavior. Classes define these objects by grouping related data members and functions together, and objects are instantiated from classes. Some key aspects of OOP include:
1. Encapsulation which involves hiding implementation details within classes and exposing a public interface.
2. Inheritance which allows a derived class to extend a base class while retaining shared properties.
3. Dynamic binding which enables polymorphic behavior where derived classes can exhibit different behavior than base classes in the same context.
Object Oriented Programming involves modeling real-world entities as objects that encapsulate both data and behavior. Classes define these objects by grouping the data (attributes) and functions (methods) that operate on that data. In C++, classes use access specifiers like public and private to control whether data and methods can be accessed from outside the class or only within the class. Methods are defined either inside or outside the class using the scope resolution operator. Objects are instantiated from classes and their methods and data can be accessed using dot or arrow operators.
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.
The document discusses object-oriented programming concepts in C#, including classes, constructors, destructors, and access modifiers. It provides examples of how to define classes with properties, methods, and constructors. It also explains the differences between public, private, and protected access modifiers and how they control accessibility of class members both within and outside of a class. The document contains code examples demonstrating the usage of classes, constructors, and access modifiers in C#.
The document discusses various concepts related to objects and classes in C++ including copy constructors, shallow vs deep copy, customizing copy constructors, immutable objects, static vs instance members, friend functions and classes, const member functions and objects, and the difference between structs and classes. Specifically, it provides examples to illustrate deep copying of objects containing dynamic memory, implementing copy constructors for deep copy, using static member functions and data, allowing access to private members using friend functions and classes, and ensuring objects are immutable using const.
This document discusses object-oriented programming and C++. It introduces classes and objects, explaining that classes are user-defined data types that contain data members and member functions, while objects are instances of classes. It provides examples of defining a class called Student and creating objects from it. The document also covers abstract data types and the advantages of abstraction.
New and delete are a thing of the past, with the new features in C++14 and beyond (such as smart pointers and move semantics) memory management is easier and safer. Learn how to use the new constructs of C++14 and beyond to create, move, and free objects in a safer and more efficient manner.
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 friend functions and classes, which can access private and protected members of another class. It provides examples of declaring friend functions and classes, and demonstrates how friend functions can modify private variables, while non-friend functions cannot. The document also covers static class members, which are shared by all objects of a class, and proxy classes, which hide the implementation of another class through a public interface.
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
Slides I prepared for the 29 January 2014 Ecma TC39 meeting, on Value Objects in JS, an ES7 proposal -- this one shotgunned the roadmap-space of declarative syntax, to find the right amount per TC39 (nearly zero, turns out).
1. The document discusses different approaches to binding user interface elements like text boxes and lists to model objects in Java applications.
2. It introduces transformers, filters, and adapters as ways to handle type mismatches and validate user input when binding between views and models.
3. Transformers convert between the types of the model and view, filters validate user input before it reaches the model, and adapters customize how model objects appear in user interface elements like lists and dropdowns.
1. C++ templates allow for the creation of generic classes and functions that can work with multiple data types.
2. Class templates define a class that can be instantiated with different data types specified within angle brackets.
3. A template class definition includes the template parameters, class members, and function definitions, while a specific class is created by specifying the data type.
The document discusses data frames in R. It defines data frames as a two-dimensional structure that can store different data types across rows and columns. It then demonstrates how to create data frames from vectors, access elements, perform operations like subsetting, merging, and applying functions using lapply() and sapply(). Data frames allow storing and manipulating tabular data in R.
This document discusses how to find the composite of two functions and the resulting domain. It defines the composite function f o g(x) as the successive application of functions f and g, with f(g(x)). The domain of the composite function is the set of elements x in the domain of g where g(x) is in the domain of f, meaning the range of g must be within the domain of f. Several examples are provided of evaluating composite functions and finding their domains. Classwork and homework assignments are also listed.
This document discusses various concepts related to classes and objects in C++, including member functions, data members, constructors, destructors, friend functions, and nested classes. It provides examples of defining member functions inside and outside the class, different access specifiers for data members, examples of friend functions and classes, returning objects from functions, arrays of objects, and nested classes. It also discusses constructors in more detail, including overloaded constructors, copy constructors, dynamic initialization of objects, constructors for primitive types, and constructors with default arguments.
The document discusses using ES6 features in real-world applications. It provides examples of using arrow functions, classes, destructuring, template literals, and default parameters to write cleaner code. It also discusses tools for enabling ES6 features that are not yet fully supported, such as transpilers, and flags in Node.js and Chrome to enable more experimental features. Overall, the document advocates adopting ES6 features that make code more concise and readable.
Implementation details and performance traits of generics in .NET, Java and C++. Presentation for the Jerusalem .NET/C++ User Group by Sasha Goldshtein.
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.
Example for Abstract Class and Interface.pdfrajaratna4
This document discusses abstract classes and interfaces in C++. It provides three examples:
1) An abstract Shape class with pure virtual calculateArea() function is implemented by Square and Circle classes. This enforces that derived classes provide an implementation of calculateArea().
2) A Shape interface with pure virtual draw() function is implemented by Rectangle and Circle classes, each providing their own draw() method.
3) Another abstract Shape class with pure virtual getArea() function and width/height properties is implemented by Rectangle and Triangle classes, each providing their own getArea() calculation based on width and height.
The document discusses various object-oriented programming concepts in C++ like classes, objects, member functions, data members, constructors, destructors, friend functions, and namespaces. It provides examples of defining classes with data members and member functions, declaring objects of a class, and using constructors and destructors. It also explains concepts like overloaded constructors, copy constructors, nested classes, dynamic initialization of objects, and friend functions.
This document provides an overview of classes and objects in C++, including:
1) Access specifiers like public, private, and protected and how they control access to class members.
2) Constant objects and functions, which can only access but not modify member data.
3) Arrays of objects, where an array stores multiple objects of the same class.
4) Passing objects as function arguments and returning objects from functions.
C# is similar to C++ but easier to use, as it does not support pointers, multiple inheritance, header files or global variables. Everything must live within a class or struct. The basic syntax will be familiar to C++ programmers. Key features include properties, interfaces, foreach loops, and delegates for event handling. Properties allow custom getter and setter logic and are preferred over public fields. Delegates provide a type-safe way to link methods, and events build on this to prevent issues with multicast delegates. Generics and assemblies are analogous to C++ templates and deployment units.
Вениамин Гвоздиков: Особенности использования DTrace Yandex
Вначале рассмотрим возможности DTrace для трассировки приложений в реальном времени. Затем перейдём на особенности его использования на разных ОС и их ограничения. В конце будут приведены задания с динамически создаваемыми пробами для прикладной разработки на LUA в Tarantool.
The document discusses various concepts related to objects and classes in C++ including copy constructors, shallow vs deep copy, customizing copy constructors, immutable objects, static vs instance members, friend functions and classes, const member functions and objects, and the difference between structs and classes. Specifically, it provides examples to illustrate deep copying of objects containing dynamic memory, implementing copy constructors for deep copy, using static member functions and data, allowing access to private members using friend functions and classes, and ensuring objects are immutable using const.
This document discusses object-oriented programming and C++. It introduces classes and objects, explaining that classes are user-defined data types that contain data members and member functions, while objects are instances of classes. It provides examples of defining a class called Student and creating objects from it. The document also covers abstract data types and the advantages of abstraction.
New and delete are a thing of the past, with the new features in C++14 and beyond (such as smart pointers and move semantics) memory management is easier and safer. Learn how to use the new constructs of C++14 and beyond to create, move, and free objects in a safer and more efficient manner.
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 friend functions and classes, which can access private and protected members of another class. It provides examples of declaring friend functions and classes, and demonstrates how friend functions can modify private variables, while non-friend functions cannot. The document also covers static class members, which are shared by all objects of a class, and proxy classes, which hide the implementation of another class through a public interface.
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
Slides I prepared for the 29 January 2014 Ecma TC39 meeting, on Value Objects in JS, an ES7 proposal -- this one shotgunned the roadmap-space of declarative syntax, to find the right amount per TC39 (nearly zero, turns out).
1. The document discusses different approaches to binding user interface elements like text boxes and lists to model objects in Java applications.
2. It introduces transformers, filters, and adapters as ways to handle type mismatches and validate user input when binding between views and models.
3. Transformers convert between the types of the model and view, filters validate user input before it reaches the model, and adapters customize how model objects appear in user interface elements like lists and dropdowns.
1. C++ templates allow for the creation of generic classes and functions that can work with multiple data types.
2. Class templates define a class that can be instantiated with different data types specified within angle brackets.
3. A template class definition includes the template parameters, class members, and function definitions, while a specific class is created by specifying the data type.
The document discusses data frames in R. It defines data frames as a two-dimensional structure that can store different data types across rows and columns. It then demonstrates how to create data frames from vectors, access elements, perform operations like subsetting, merging, and applying functions using lapply() and sapply(). Data frames allow storing and manipulating tabular data in R.
This document discusses how to find the composite of two functions and the resulting domain. It defines the composite function f o g(x) as the successive application of functions f and g, with f(g(x)). The domain of the composite function is the set of elements x in the domain of g where g(x) is in the domain of f, meaning the range of g must be within the domain of f. Several examples are provided of evaluating composite functions and finding their domains. Classwork and homework assignments are also listed.
This document discusses various concepts related to classes and objects in C++, including member functions, data members, constructors, destructors, friend functions, and nested classes. It provides examples of defining member functions inside and outside the class, different access specifiers for data members, examples of friend functions and classes, returning objects from functions, arrays of objects, and nested classes. It also discusses constructors in more detail, including overloaded constructors, copy constructors, dynamic initialization of objects, constructors for primitive types, and constructors with default arguments.
The document discusses using ES6 features in real-world applications. It provides examples of using arrow functions, classes, destructuring, template literals, and default parameters to write cleaner code. It also discusses tools for enabling ES6 features that are not yet fully supported, such as transpilers, and flags in Node.js and Chrome to enable more experimental features. Overall, the document advocates adopting ES6 features that make code more concise and readable.
Implementation details and performance traits of generics in .NET, Java and C++. Presentation for the Jerusalem .NET/C++ User Group by Sasha Goldshtein.
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.
Example for Abstract Class and Interface.pdfrajaratna4
This document discusses abstract classes and interfaces in C++. It provides three examples:
1) An abstract Shape class with pure virtual calculateArea() function is implemented by Square and Circle classes. This enforces that derived classes provide an implementation of calculateArea().
2) A Shape interface with pure virtual draw() function is implemented by Rectangle and Circle classes, each providing their own draw() method.
3) Another abstract Shape class with pure virtual getArea() function and width/height properties is implemented by Rectangle and Triangle classes, each providing their own getArea() calculation based on width and height.
The document discusses various object-oriented programming concepts in C++ like classes, objects, member functions, data members, constructors, destructors, friend functions, and namespaces. It provides examples of defining classes with data members and member functions, declaring objects of a class, and using constructors and destructors. It also explains concepts like overloaded constructors, copy constructors, nested classes, dynamic initialization of objects, and friend functions.
This document provides an overview of classes and objects in C++, including:
1) Access specifiers like public, private, and protected and how they control access to class members.
2) Constant objects and functions, which can only access but not modify member data.
3) Arrays of objects, where an array stores multiple objects of the same class.
4) Passing objects as function arguments and returning objects from functions.
C# is similar to C++ but easier to use, as it does not support pointers, multiple inheritance, header files or global variables. Everything must live within a class or struct. The basic syntax will be familiar to C++ programmers. Key features include properties, interfaces, foreach loops, and delegates for event handling. Properties allow custom getter and setter logic and are preferred over public fields. Delegates provide a type-safe way to link methods, and events build on this to prevent issues with multicast delegates. Generics and assemblies are analogous to C++ templates and deployment units.
Вениамин Гвоздиков: Особенности использования DTrace Yandex
Вначале рассмотрим возможности DTrace для трассировки приложений в реальном времени. Затем перейдём на особенности его использования на разных ОС и их ограничения. В конце будут приведены задания с динамически создаваемыми пробами для прикладной разработки на LUA в Tarantool.
06-04-2024 - NYC Tech Week - Discussion on Vector Databases, Unstructured Data and AI
Round table discussion of vector databases, unstructured data, ai, big data, real-time, robots and Milvus.
A lively discussion with NJ Gen AI Meetup Lead, Prasad and Procure.FYI's Co-Found
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...Social Samosa
The Modern Marketing Reckoner (MMR) is a comprehensive resource packed with POVs from 60+ industry leaders on how AI is transforming the 4 key pillars of marketing – product, place, price and promotions.
The Building Blocks of QuestDB, a Time Series Databasejavier ramirez
Talk Delivered at Valencia Codes Meetup 2024-06.
Traditionally, databases have treated timestamps just as another data type. However, when performing real-time analytics, timestamps should be first class citizens and we need rich time semantics to get the most out of our data. We also need to deal with ever growing datasets while keeping performant, which is as fun as it sounds.
It is no wonder time-series databases are now more popular than ever before. Join me in this session to learn about the internal architecture and building blocks of QuestDB, an open source time-series database designed for speed. We will also review a history of some of the changes we have gone over the past two years to deal with late and unordered data, non-blocking writes, read-replicas, or faster batch ingestion.
Learn SQL from basic queries to Advance queriesmanishkhaire30
Dive into the world of data analysis with our comprehensive guide on mastering SQL! This presentation offers a practical approach to learning SQL, focusing on real-world applications and hands-on practice. Whether you're a beginner or looking to sharpen your skills, this guide provides the tools you need to extract, analyze, and interpret data effectively.
Key Highlights:
Foundations of SQL: Understand the basics of SQL, including data retrieval, filtering, and aggregation.
Advanced Queries: Learn to craft complex queries to uncover deep insights from your data.
Data Trends and Patterns: Discover how to identify and interpret trends and patterns in your datasets.
Practical Examples: Follow step-by-step examples to apply SQL techniques in real-world scenarios.
Actionable Insights: Gain the skills to derive actionable insights that drive informed decision-making.
Join us on this journey to enhance your data analysis capabilities and unlock the full potential of SQL. Perfect for data enthusiasts, analysts, and anyone eager to harness the power of data!
#DataAnalysis #SQL #LearningSQL #DataInsights #DataScience #Analytics
Enhanced Enterprise Intelligence with your personal AI Data Copilot.pdfGetInData
Recently we have observed the rise of open-source Large Language Models (LLMs) that are community-driven or developed by the AI market leaders, such as Meta (Llama3), Databricks (DBRX) and Snowflake (Arctic). On the other hand, there is a growth in interest in specialized, carefully fine-tuned yet relatively small models that can efficiently assist programmers in day-to-day tasks. Finally, Retrieval-Augmented Generation (RAG) architectures have gained a lot of traction as the preferred approach for LLMs context and prompt augmentation for building conversational SQL data copilots, code copilots and chatbots.
In this presentation, we will show how we built upon these three concepts a robust Data Copilot that can help to democratize access to company data assets and boost performance of everyone working with data platforms.
Why do we need yet another (open-source ) Copilot?
How can we build one?
Architecture and evaluation
3. 3
Friend Functions/Classes
Friend functions
A 'friend' function has access to all
'private' members of the class for which it
is a 'friend'.
To declare a 'friend' function, include its
prototype within the class, preceding it
with the C++ keyword 'friend'.
4. 4
COLLISION PROBLEM
APPROACHES: SIMPLE RECTANGLE , SHRUNKEN RECT,
SPRITE IMAGE
Sample application that can benefit from friend classes/functions
• One class for each moving object
• One instance of a class doesn’t know the boundaries of
other moving objects
• Data members of each object is hidden and protected from
other moving objects
5. 5
COLLISION PROBLEM
Friend functions/class by-pass object data hiding
Class Wall
class TANK
Friend
function
Intermediary function that is
permitted to manipulate the
data members of both Tank
and Wall classes
6. 6
COLLISION PROBLEM
Friend functions/class by-pass object data hiding
Class Wall
class TANK
Friend to class Tank
Function(s) permitted
to manipulate the data
members of class
Tank
Data members
of class Tank
7. 7
COLLISION PROBLEM
How to detect
collision between
objects?
• not convincing enough!
Overlapping
region
SIMPLE RECTANGLE APPROACH
8. 8
COLLISION PROBLEM
How to detect
collision between
objects?
• can be a major
bottleneck in
performance to get a
decent animation
SPRITE IMAGE APPROACH
Overlapping
region
9. 9
COLLISION PROBLEM
Overlapping
region
How to detect
collision between
objects?
• Fast
• Simple to implement
• perfect for a game
with many moving objects
SHRUNKEN RECTANGLE APPROACH
12. 12
COLLISION PROBLEM
Sample Collision Cases:
(t.x1 >= ledge.x1) && (t.x1 <= ledge.x2)
if( ((t.x1 >= ledge.x1) && (t.x1 <= ledge.x2) && (t.y1 >= ledge.y1) && (t.y1 <= ledge.y2)) ||
((t.x1 >= ledge.x1) && (t.x1 <= ledge.x2) && (t.y2 >= ledge.y1) && (t.y2 <= ledge.y2)) ||
((t.x2 >= ledge.x1) && (t.x2 <= ledge.x2) && (t.y1 >= ledge.y1) && (t.y1 <= ledge.y2)) ||
((t.x2 >= ledge.x1) && (t.x2 <= ledge.x2) && (t.y2 >= ledge.y1) && (t.y2 <= ledge.y2)) )
LEDGE
(x1,y1)
(x2,y2)
(x1,y1)
(x2,y2)
TANK
Note: This example is
only using the device
system of coordinates
and is therefore not
scalable.
13. 13
COLLISION PROBLEM
Sample Collision Cases:
(t.x1 >= ledge.x1) && (t.x1 <= ledge.x2)
if( ((t.x1 >= ledge.x1) && (t.x1 <= ledge.x2) && (t.y1 >= ledge.y1) && (t.y1 <= ledge.y2)) ||
((t.x1 >= ledge.x1) && (t.x1 <= ledge.x2) && (t.y2 >= ledge.y1) && (t.y2 <= ledge.y2)) ||
((t.x2 >= ledge.x1) && (t.x2 <= ledge.x2) && (t.y1 >= ledge.y1) && (t.y1 <= ledge.y2)) ||
((t.x2 >= ledge.x1) && (t.x2 <= ledge.x2) && (t.y2 >= ledge.y1) && (t.y2 <= ledge.y2)) )
LEDGE
(x1,y1)
(x2,y2)
(x1,y1)
(x2,y2)
TANK
Note: This example is
only using the device
system of coordinates
and is therefore not
scalable.
14. 14
COLLISION PROBLEM
LEDGE
(x1,y1)
(x2,y2)
(x1,y1)
(x2,y2)
TANK
Sample Collision Cases:
(t.x2 >= ledge.x1) && (t.x2 <= ledge.x2)
if( ((t.x1 >= ledge.x1) && (t.x1 <= ledge.x2) && (t.y1 >= ledge.y1) && (t.y1 <= ledge.y2)) ||
((t.x1 >= ledge.x1) && (t.x1 <= ledge.x2) && (t.y2 >= ledge.y1) && (t.y2 <= ledge.y2)) ||
((t.x2 >= ledge.x1) && (t.x2 <= ledge.x2) && (t.y1 >= ledge.y1) && (t.y1 <= ledge.y2)) ||
((t.x2 >= ledge.x1) && (t.x2 <= ledge.x2) && (t.y2 >= ledge.y1) && (t.y2 <= ledge.y2)) )
Note: This example is
only using the device
system of coordinates
and is therefore not
scalable.
15. 15
COLLISION PROBLEM
Sample Collision Cases:
(t.x2 >= ledge.x1) && (t.x2 <= ledge.x2)
if( ((t.x1 >= ledge.x1) && (t.x1 <= ledge.x2) && (t.y1 >= ledge.y1) && (t.y1 <= ledge.y2)) ||
((t.x1 >= ledge.x1) && (t.x1 <= ledge.x2) && (t.y2 >= ledge.y1) && (t.y2 <= ledge.y2)) ||
((t.x2 >= ledge.x1) && (t.x2 <= ledge.x2) && (t.y1 >= ledge.y1) && (t.y1 <= ledge.y2)) ||
((t.x2 >= ledge.x1) && (t.x2 <= ledge.x2) && (t.y2 >= ledge.y1) && (t.y2 <= ledge.y2)) )
LEDGE
(x1,y1)
(x2,y2)
(x1,y1)
(x2,y2)
TANK
Note: This example is
only using the device
system of coordinates
and is therefore not
scalable.
16. 16
Friend Functions/Classes
class T {
public:
friend void a();
int m();
private: // ...
};
void a() {// can access
// private data in T...}
class S {
public:
friend int T::m();
//...
};
class X {
public:
friend class T;
//...
};
• Global function a() can access
private data in T
• m() can access private data in
S
• all functions of T can access private
data in X
friends should be used with caution:
they by-pass C++’s data hiding
principle.
It is the responsibility of the code for
which access is to be given to say
who it’s friends are - i.e. who does
it trust!
17. 17
Friend Functions/Classes
class Demo {
friend void Change( Demo obj );
public:
Demo(double x0=0.0, int y0=0.0):x(x0),y(y0){}
void print();
private:
double x; int y;
};
void Demo::print(){
cout << endl << "This is x " << x << endl;
cout << "This is y " << y << endl;
}
void Change( Demo obj ) {
obj.x += 100;
obj.y += 200;
cout << "This is obj.x" << obj.x << endl;
cout << "This is obj.y" << obj.y << endl;
}
18. 18
Friend Functions/Classes
#include <iostream>
using namespace std;
const int DaysInMonth[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
enum Months { unused, January, February, March, April, May, June,
July, August, September, October, November, December };
const char *MonthNames[]={"Unused", "January", "February", "March", "April", "May",
"June",
"July", "August", "September", "October", "November", "December" };
class Date{
friend bool before( Date & d1, Date & d2 );
public:
Date( int d=1, int m=1, int y=1970 ){ // do not use initialiser list in constructor
setMonth( m); // as here we want to reuse the checks
setDay(d); // in the set methods
setYear(y); // remember month is used to verify day validity
}
~Date(){} // no special needs for destructor
Date( const Date & date ){ // supply an explicit copy constructor
day = date.day;
month = date.month;
year = date.year;
}
int getDay(){ return day; }
void setDay( int d ){
if( d > 0 && d <= DaysInMonth[month] ){
day = d;
}
else{
cerr << "Invalid Day value " << d << endl;
exit(1);
}
}
int getMonth(){ return month; }
void setMonth( int m ){
if( m >= 1 && m <= 12 ){
month = m;
}
else{
cerr << "Invalid Month value " << m << endl;
exit(1);
}
}
int getYear(){return year;}
void setYear( int y ){
// no restrictions placed on year
year = y;
}
void print(){
cout << day << " of " << MonthNames[month] << ", " << year << endl;
}
private:
int day;
int month;
int year;
};
• Continued on next slide…
19. 19
Friend Functions/Classes
bool before( Date & d1, Date & d2 ); // prototype
int main(){ // test the Calendar collection
Date today;
Date lecture11( 6, 8, 2008 );
today.setMonth( August );
today.setDay( 7 );
today.setYear( 2008 );
today.print();
lecture11.print();
if( before( lecture11 , today ) )
cout << "lecture11 was before today" << endl;
Date tomorrow( 8, 8, 2008 );
if( before( tomorrow , today ) )
cout << "tomorrow was before today" << endl;
else
cout << "tomorrow was not before today" << endl;
return 0;
}
// return true if Date1 is before Date2
bool before( Date & d1, Date & d2 ){
if( d1.year < d2.year )
return true;
else if( d1.year == d2.year ){
if( d1.month < d2.month )
return true;
else if( d1.month == d2.month ){
if( d1.day < d2.day )
return true;
}
}
return false;
}
• We wanted the global
before() function to
have access to the
internals of the Date
class
• Date declares it as a
friend function
• Example output:
7 of August, 2008
6 of August, 2008
lecture11 was before today
tomorrow was not before today
21. 21
Friend Functions/Classes
Questions
1. Is there any difference between List x; and List x();?
2. Is the default constructor for Fred always Fred::Fred()?
3. Should constructors use "initializer lists" or "assignment"?
4. How do you know when to declare a function as a member
function or a friend function in your class?
From: C++ FAQ Lite
http://www.parashift.com
22. 22
Friend Functions/Classes
The following questions pertain to a class called Circle.
a) The only element in a circle considered unique is the radius. Write
one line of code that declares the necessary data member.
b) In which section of the class does this data member get put?
c) Write the prototype for the constructor which takes a radius as its
parameter.
d) In which section of the class does this constructor get put?
e) Write the function definition for the member function Area which
computes the area of a Circle object. (Just use 3.14159 for Pi. And
remember that area of a circle of radius R is given by: R2.)