This document provides information about a C++ course for the second semester. It includes the course name "B Sc IT", subject name "C++", and semester "II".
Constructors and destructors are special member functions in C++ that are used to initialize and cleanup objects. Constructors are called automatically when an object is created and are used to set initial values for object attributes. Destructors are called automatically when an object is destroyed and can perform cleanup tasks. There are different types of constructors like default, parameterized, and copy constructors. Constructors and destructors have the same name as the class but constructors don't have a return type while destructors are preceded by a tilde (~).
C++ - Constructors,Destructors, Operator overloading and Type conversionHashni T
This document discusses constructors and destructors in C++. It begins by defining constructors as special methods that are automatically called when an object is created. Constructors initialize class data members and have the same name as the class. Destructors are used to destroy objects and clean up memory. The document then covers topics like parameterized constructors, copy constructors, dynamic constructors, characteristics of constructors and destructors, and operator overloading and type conversions.
This document discusses various C++ concepts related to functions including:
- Default pointers which receive addresses passed to called functions.
- Reference variables which receive the reference of an actual variable passed to a function. Changing the reference variable directly changes the actual variable.
- Inline functions which eliminate context switching when defined inside a class or declared with the inline keyword.
- Friend functions which have access to private/protected members of a class they are declared as a friend to.
Virtual functions allow polymorphism by implementing a common interface in base and derived classes that can be called dynamically at runtime. They are declared with the virtual keyword in the base class and overridden with the same name and parameters in derived classes. Pure virtual functions are virtual functions without a body declared using =0, making a class abstract that cannot be instantiated until overridden in derived classes. Virtual destructors ensure the correct derived class destructor is called when deleting polymorphic objects through a base class pointer.
Constructors are used to initialize objects and allocate memory. A constructor has the same name as its class and is invoked when an object is created. There are different types of constructors including default, parameterized, copy, and dynamic constructors. A destructor is used to destroy objects and does not have any arguments or return values.
1. A structure is a collection of variables under a single name. Variables within a structure can be of different data types like int, float, etc.
2. To declare a structure, the keyword struct is used followed by the structure name in braces. To define a structure variable, the data type is the structure name followed by the variable name.
3. Structure members are accessed using the dot operator between the structure variable name and member name.
Constructors and destructors are special member functions in C++ that are used for initializing objects and cleaning up resources. Constructors are called automatically when an object is created and are used to initialize member variables. Destructors are called when an object is destroyed in order to clean up resources. There are different types of constructors like default, parameterized, and copy constructors. Constructors can be invoked implicitly, explicitly, or through initialization. Destructors have the same name as the class preceded by a tilde and are used to de-allocate memory allocated by the constructor.
Constructors and destructors are special member functions in C++ that are used to initialize and cleanup objects. Constructors are called automatically when an object is created and are used to set initial values for object attributes. Destructors are called automatically when an object is destroyed and can perform cleanup tasks. There are different types of constructors like default, parameterized, and copy constructors. Constructors and destructors have the same name as the class but constructors don't have a return type while destructors are preceded by a tilde (~).
C++ - Constructors,Destructors, Operator overloading and Type conversionHashni T
This document discusses constructors and destructors in C++. It begins by defining constructors as special methods that are automatically called when an object is created. Constructors initialize class data members and have the same name as the class. Destructors are used to destroy objects and clean up memory. The document then covers topics like parameterized constructors, copy constructors, dynamic constructors, characteristics of constructors and destructors, and operator overloading and type conversions.
This document discusses various C++ concepts related to functions including:
- Default pointers which receive addresses passed to called functions.
- Reference variables which receive the reference of an actual variable passed to a function. Changing the reference variable directly changes the actual variable.
- Inline functions which eliminate context switching when defined inside a class or declared with the inline keyword.
- Friend functions which have access to private/protected members of a class they are declared as a friend to.
Virtual functions allow polymorphism by implementing a common interface in base and derived classes that can be called dynamically at runtime. They are declared with the virtual keyword in the base class and overridden with the same name and parameters in derived classes. Pure virtual functions are virtual functions without a body declared using =0, making a class abstract that cannot be instantiated until overridden in derived classes. Virtual destructors ensure the correct derived class destructor is called when deleting polymorphic objects through a base class pointer.
Constructors are used to initialize objects and allocate memory. A constructor has the same name as its class and is invoked when an object is created. There are different types of constructors including default, parameterized, copy, and dynamic constructors. A destructor is used to destroy objects and does not have any arguments or return values.
1. A structure is a collection of variables under a single name. Variables within a structure can be of different data types like int, float, etc.
2. To declare a structure, the keyword struct is used followed by the structure name in braces. To define a structure variable, the data type is the structure name followed by the variable name.
3. Structure members are accessed using the dot operator between the structure variable name and member name.
Constructors and destructors are special member functions in C++ that are used for initializing objects and cleaning up resources. Constructors are called automatically when an object is created and are used to initialize member variables. Destructors are called when an object is destroyed in order to clean up resources. There are different types of constructors like default, parameterized, and copy constructors. Constructors can be invoked implicitly, explicitly, or through initialization. Destructors have the same name as the class preceded by a tilde and are used to de-allocate memory allocated by the constructor.
The document discusses various concepts related to inheritance in C++ including types of inheritance (single, multiple, hierarchical, multilevel, hybrid), defining derived classes, visibility modes (private, public), constructors and destructors in derived classes, virtual base classes, virtual functions, pure virtual functions, and abstract base classes. It provides examples and explanations for each concept.
1. The document discusses various concepts related to functions in C++ such as function prototypes, passing arguments by reference, default arguments, inline functions, function overloading, and friend functions.
2. It provides examples to explain concepts like passing arguments by reference allows altering the original variable values, a friend function can access private members of a class, and function overloading allows using the same function name for different tasks based on the argument types.
3. The key benefits of concepts like inline functions, passing by reference, and function overloading are also summarized.
This document discusses different types of functions in C++ including: library functions, user-defined functions, overloaded functions, inline functions, friend functions, static functions, constructor functions, destructor functions, and virtual functions. It provides examples and definitions for each type of function.
Namespace defines a scope for identifiers used in a program. Reference variables provide an alias for previously defined variables, and their main purpose is passing arguments to functions. C++ defines new and delete operators for allocating and freeing memory. The main() cannot directly access private data members; they must use member functions. A private member function can only be called by another member function of its class. A static member function can be called using the class name as class-name::function-name.
The document discusses key concepts in C++ classes including encapsulation, information hiding, access specifiers, and constructors. It defines a class as a way to combine attributes and behaviors of real-world objects into a single unit. A class uses encapsulation to associate code and data, and information hiding to secure data from direct access. Access specifiers like public, private, and protected determine member visibility. Constructors are special member functions that initialize objects upon instantiation.
The document defines and provides examples of polymorphism in object-oriented programming. It discusses two types of polymorphism: static and dynamic. Static polymorphism is resolved at compile-time through function overloading and operator overloading, while dynamic polymorphism uses virtual functions and is resolved at run-time. Virtual functions, pure virtual functions, and abstract classes are also explained as key aspects of implementing dynamic polymorphism.
Encapsulation isolates the internal complexity of an object's operation from the rest of the application. Inheritance allows one class to reuse the state and behavior of another class. Polymorphism allows a client to treat different objects in the same way even if they were created from different classes and exhibit different behaviors.
C/C++ Programming interview questions and answers document discusses key concepts in C++ including encapsulation, inheritance, polymorphism, constructors, destructors, copy constructors, references, virtual functions, abstract classes, and memory alignment. The document provides definitions and examples to explain each concept.
Xbase - Implementing Domain-Specific Languages for Javameysholdt
This document discusses using Xtext to implement domain-specific languages for Java. Xtext allows defining the grammar of a DSL and generates an IDE and runtime. Key points:
- Xtext generates editors, compilers/interpreters, debuggers from a DSL grammar. The grammar reuse and customization allow adapting Xtext to different needs.
- Xbase provides a reusable expression language that can be embedded in Xtext DSLs, providing features like lambda expressions, extension methods, and type inference.
- A JvmModel inference performs a model-to-model transformation to map DSL models to equivalent Java classes, providing context for linking, type system, and compilation of DSL expressions.
This document provides an overview of object-oriented programming concepts in C++, including classes, objects, encapsulation, inheritance, polymorphism, and more. Key concepts are defined, such as classes containing data members and methods. Inheritance allows derived classes to inherit properties of base classes. Polymorphism allows calling the correct overridden method at runtime based on the object type. Virtual functions provide late binding so the correct derived class method is called.
The document discusses various concepts related to C++ classes including:
1. Structure definitions, accessing structure members using dot operator and pointers. Class definitions include data members and member functions.
2. Class objects are created using the class name followed by the object name. Class members are accessed using dot operator. Member functions can be defined inside or outside the class.
3. Access specifiers like private, public, and protected control access to class members. Constructors and destructors are special member functions for object initialization and destruction.
The document discusses fundamentals of object-oriented programming. It defines objects as software bundles that model real-world objects using variables to represent states and methods to represent behaviors. Classes are blueprints that define common variables and methods for objects. Objects interact by sending messages to each other specifying a method and parameters. Object-oriented principles of abstraction, encapsulation, inheritance and polymorphism are covered.
Functors, Applicatives and Monads In ScalaKnoldus Inc.
The document discusses functors, applicatives, and monads. It defines each concept and provides examples. Functors allow mapping a function over a wrapped value using map. Applicatives allow applying a function wrapped in a context to a value wrapped in a context using apply. Monads allow applying a function that returns a wrapped value to a wrapped value using flatMap. Examples of each include Option for functors, lists for applicatives, and futures for monads.
Utah Code Camp, Spring 2016. http://utahcodecamp.com In this presentation I describe modern C++. Modern C++ assumes features introduced in the C++11/14 standard. An overview of the new features is presented and some idioms for mdoern C++ based on those features are presented.
The document discusses pointers in C programming. It defines pointers as variables that contain memory addresses and can point to different data types. It covers pointer arithmetic, passing pointers to functions, and using pointers with arrays, including arrays of pointers. Functions can be called by value by passing the variable itself, or by reference by passing the memory address of the variable using pointers, allowing the function to modify the original variable. Pointer notation can be used to access elements of two-dimensional arrays.
1) A constructor in Java is a special method that is used to initialize objects and is called when an object is created. It can set initial values for object attributes.
2) There are different types of constructors including default, parameterized, and copy constructors. The default constructor takes no parameters, parameterized constructors take parameters to initialize objects with different values, and copy constructors are used to create a copy of an object.
3) Constructor overloading allows a class to have multiple constructors with the same name but different parameters, allowing objects to be initialized in different ways.
This document provides an introduction to classes and objects in C++. It defines key concepts like class, object, member functions, access specifiers, and arrays of objects. It also discusses defining objects of a class, accessing class members, passing objects as function arguments, and the differences between classes and structures in C++.
This document discusses pointers in C programming. It defines pointers as variables that contain the memory addresses of other variables. It covers pointer variable declarations and initialization, the need for pointers, pointer operators like & and *, passing arguments by reference using pointers, pointer arithmetic, the relationship between pointers and arrays, and arrays of pointers. Pointers allow indirect access to variables, pass by reference, dynamic memory allocation, and are used to implement data structures like linked lists.
This document discusses double pointers or pointer-to-pointers in C. A double pointer is a pointer that holds the address of another pointer variable. The first pointer stores the address of a variable, while the second pointer stores the address of the first pointer. To declare a double pointer in C, an additional asterisk is placed before the pointer variable name, such as int **ptr, which declares a pointer that points to a pointer of type int.
This document provides an overview of computers and their basic components. It defines a computer as a programmable machine designed to carry out arithmetic and logical operations. It then describes the basic computer operations of input, storage, processing, and output. Input involves entering data and programs into the system. Storage saves data and instructions permanently. Processing performs arithmetic and logical operations on the stored data. Output produces results from the data for useful information. The document concludes by describing the main hardware components of a computer including the motherboard, power supply, removable media, secondary storage, and input/output peripherals.
1. The document provides instructions on how to use Microsoft Word 2003, including how to plan documents, identify the Word window components, enter and format text, save files, scroll through documents, check for errors, and print documents.
2. Key steps outlined are planning content before writing, using toolbars and menus to format text, saving files in the desired location, using scroll bars to navigate long documents, and utilizing spelling and grammar checks to correct errors.
3. Functions like AutoComplete, Undo/Redo, Smart Tags, Print Preview, and creating envelopes are also explained to demonstrate Word's capabilities.
The document discusses various concepts related to inheritance in C++ including types of inheritance (single, multiple, hierarchical, multilevel, hybrid), defining derived classes, visibility modes (private, public), constructors and destructors in derived classes, virtual base classes, virtual functions, pure virtual functions, and abstract base classes. It provides examples and explanations for each concept.
1. The document discusses various concepts related to functions in C++ such as function prototypes, passing arguments by reference, default arguments, inline functions, function overloading, and friend functions.
2. It provides examples to explain concepts like passing arguments by reference allows altering the original variable values, a friend function can access private members of a class, and function overloading allows using the same function name for different tasks based on the argument types.
3. The key benefits of concepts like inline functions, passing by reference, and function overloading are also summarized.
This document discusses different types of functions in C++ including: library functions, user-defined functions, overloaded functions, inline functions, friend functions, static functions, constructor functions, destructor functions, and virtual functions. It provides examples and definitions for each type of function.
Namespace defines a scope for identifiers used in a program. Reference variables provide an alias for previously defined variables, and their main purpose is passing arguments to functions. C++ defines new and delete operators for allocating and freeing memory. The main() cannot directly access private data members; they must use member functions. A private member function can only be called by another member function of its class. A static member function can be called using the class name as class-name::function-name.
The document discusses key concepts in C++ classes including encapsulation, information hiding, access specifiers, and constructors. It defines a class as a way to combine attributes and behaviors of real-world objects into a single unit. A class uses encapsulation to associate code and data, and information hiding to secure data from direct access. Access specifiers like public, private, and protected determine member visibility. Constructors are special member functions that initialize objects upon instantiation.
The document defines and provides examples of polymorphism in object-oriented programming. It discusses two types of polymorphism: static and dynamic. Static polymorphism is resolved at compile-time through function overloading and operator overloading, while dynamic polymorphism uses virtual functions and is resolved at run-time. Virtual functions, pure virtual functions, and abstract classes are also explained as key aspects of implementing dynamic polymorphism.
Encapsulation isolates the internal complexity of an object's operation from the rest of the application. Inheritance allows one class to reuse the state and behavior of another class. Polymorphism allows a client to treat different objects in the same way even if they were created from different classes and exhibit different behaviors.
C/C++ Programming interview questions and answers document discusses key concepts in C++ including encapsulation, inheritance, polymorphism, constructors, destructors, copy constructors, references, virtual functions, abstract classes, and memory alignment. The document provides definitions and examples to explain each concept.
Xbase - Implementing Domain-Specific Languages for Javameysholdt
This document discusses using Xtext to implement domain-specific languages for Java. Xtext allows defining the grammar of a DSL and generates an IDE and runtime. Key points:
- Xtext generates editors, compilers/interpreters, debuggers from a DSL grammar. The grammar reuse and customization allow adapting Xtext to different needs.
- Xbase provides a reusable expression language that can be embedded in Xtext DSLs, providing features like lambda expressions, extension methods, and type inference.
- A JvmModel inference performs a model-to-model transformation to map DSL models to equivalent Java classes, providing context for linking, type system, and compilation of DSL expressions.
This document provides an overview of object-oriented programming concepts in C++, including classes, objects, encapsulation, inheritance, polymorphism, and more. Key concepts are defined, such as classes containing data members and methods. Inheritance allows derived classes to inherit properties of base classes. Polymorphism allows calling the correct overridden method at runtime based on the object type. Virtual functions provide late binding so the correct derived class method is called.
The document discusses various concepts related to C++ classes including:
1. Structure definitions, accessing structure members using dot operator and pointers. Class definitions include data members and member functions.
2. Class objects are created using the class name followed by the object name. Class members are accessed using dot operator. Member functions can be defined inside or outside the class.
3. Access specifiers like private, public, and protected control access to class members. Constructors and destructors are special member functions for object initialization and destruction.
The document discusses fundamentals of object-oriented programming. It defines objects as software bundles that model real-world objects using variables to represent states and methods to represent behaviors. Classes are blueprints that define common variables and methods for objects. Objects interact by sending messages to each other specifying a method and parameters. Object-oriented principles of abstraction, encapsulation, inheritance and polymorphism are covered.
Functors, Applicatives and Monads In ScalaKnoldus Inc.
The document discusses functors, applicatives, and monads. It defines each concept and provides examples. Functors allow mapping a function over a wrapped value using map. Applicatives allow applying a function wrapped in a context to a value wrapped in a context using apply. Monads allow applying a function that returns a wrapped value to a wrapped value using flatMap. Examples of each include Option for functors, lists for applicatives, and futures for monads.
Utah Code Camp, Spring 2016. http://utahcodecamp.com In this presentation I describe modern C++. Modern C++ assumes features introduced in the C++11/14 standard. An overview of the new features is presented and some idioms for mdoern C++ based on those features are presented.
The document discusses pointers in C programming. It defines pointers as variables that contain memory addresses and can point to different data types. It covers pointer arithmetic, passing pointers to functions, and using pointers with arrays, including arrays of pointers. Functions can be called by value by passing the variable itself, or by reference by passing the memory address of the variable using pointers, allowing the function to modify the original variable. Pointer notation can be used to access elements of two-dimensional arrays.
1) A constructor in Java is a special method that is used to initialize objects and is called when an object is created. It can set initial values for object attributes.
2) There are different types of constructors including default, parameterized, and copy constructors. The default constructor takes no parameters, parameterized constructors take parameters to initialize objects with different values, and copy constructors are used to create a copy of an object.
3) Constructor overloading allows a class to have multiple constructors with the same name but different parameters, allowing objects to be initialized in different ways.
This document provides an introduction to classes and objects in C++. It defines key concepts like class, object, member functions, access specifiers, and arrays of objects. It also discusses defining objects of a class, accessing class members, passing objects as function arguments, and the differences between classes and structures in C++.
This document discusses pointers in C programming. It defines pointers as variables that contain the memory addresses of other variables. It covers pointer variable declarations and initialization, the need for pointers, pointer operators like & and *, passing arguments by reference using pointers, pointer arithmetic, the relationship between pointers and arrays, and arrays of pointers. Pointers allow indirect access to variables, pass by reference, dynamic memory allocation, and are used to implement data structures like linked lists.
This document discusses double pointers or pointer-to-pointers in C. A double pointer is a pointer that holds the address of another pointer variable. The first pointer stores the address of a variable, while the second pointer stores the address of the first pointer. To declare a double pointer in C, an additional asterisk is placed before the pointer variable name, such as int **ptr, which declares a pointer that points to a pointer of type int.
This document provides an overview of computers and their basic components. It defines a computer as a programmable machine designed to carry out arithmetic and logical operations. It then describes the basic computer operations of input, storage, processing, and output. Input involves entering data and programs into the system. Storage saves data and instructions permanently. Processing performs arithmetic and logical operations on the stored data. Output produces results from the data for useful information. The document concludes by describing the main hardware components of a computer including the motherboard, power supply, removable media, secondary storage, and input/output peripherals.
1. The document provides instructions on how to use Microsoft Word 2003, including how to plan documents, identify the Word window components, enter and format text, save files, scroll through documents, check for errors, and print documents.
2. Key steps outlined are planning content before writing, using toolbars and menus to format text, saving files in the desired location, using scroll bars to navigate long documents, and utilizing spelling and grammar checks to correct errors.
3. Functions like AutoComplete, Undo/Redo, Smart Tags, Print Preview, and creating envelopes are also explained to demonstrate Word's capabilities.
The document discusses different types of operating systems including real-time, multi-user, single-tasking vs multi-tasking operating systems. It describes the key functions of an operating system like resource management, data management, and job management. It also explains the two main types of user interfaces - command line interface and graphical user interface. Finally, it provides details about popular operating systems like UNIX, MS-DOS, Windows, and Linux.
The document discusses various strategies for organizing and managing computer files and folders, including creating, naming, copying, moving, and deleting files and folders. It also covers exploring and navigating files and folders using Windows Explorer, understanding file paths, and working with compressed files.
The document provides an overview of various programming techniques including procedural programming, modular programming, and object-oriented programming. It then discusses key concepts in C++ like data types, variables, constants, input/output streams, and basic program structure. A sample "Hello World" program is included and explained to demonstrate fundamental C++ syntax and program execution.
The document provides information about an exception handling course for the subject of C++ during the second semester. It includes details about try, catch, and throw keywords used for exception handling in C++ as well as custom exceptions using exception classes. Standard exceptions and namespaces are also briefly discussed.
1. C++ arrays allow storing multiple values of the same type in contiguous memory locations accessed via an index. Multidimensional arrays can store arrays of arrays.
2. Pointers store the address of other variables in memory. Pointer variables can be initialized with the address of another variable using the & operator and dereferenced using *.
3. Classes in C++ are user-defined data types that can contain data members and member functions. Class objects can be declared to access members.
Constructors initialize objects when they are created and can be used to set initial values for object attributes. Destructors are called automatically when objects are destroyed. This document discusses various types of constructors like default, copy, parameterized constructors. It also covers constructor overloading and destructors.
The document discusses constructors and destructors in C++. It states that constructors and destructors are special member functions that control how objects are created, initialized, copied, and destroyed. Constructors have the same name as the class and are executed when an object is declared, while destructors are preceded by a tilde symbol and are executed when objects go out of scope. The document provides examples of defining different types of constructors, such as default, parameterized, copy constructors, and multiple constructors. It also demonstrates how arrays of objects can be initialized using constructors and how constructors and destructors are automatically called by the compiler.
The constructor constructs objects and initializes member variables when an object is created. The destructor destroys objects when they are no longer needed. Constructors and destructors have the same name as the class and are automatically called by the compiler. Constructors can be overloaded and can have default arguments to initialize objects differently. Copy constructors allow objects to be initialized by passing references of other objects. Destructors destroy objects before they go out of scope.
The document discusses functions in C programming. The key points are:
1. A function is a block of code that performs a specific task. Functions allow code reusability and modularity.
2. main() is the starting point of a C program where execution begins. User-defined functions are called from main() or other functions.
3. Functions can take arguments and return values. There are different ways functions can be defined based on these criteria.
4. Variables used within a function have local scope while global variables can be accessed from anywhere. Pointers allow passing arguments by reference.
This document discusses various C++ constructor and destructor concepts including:
- Constructors are special methods that initialize object data members when created and can be parameterized to initialize with different values.
- Classes can contain multiple constructors and constructors with default arguments.
- Copy constructors initialize objects using another object of the same class.
- Const objects can only access const member functions and attempts to modify will generate errors.
- Destructors are used to destroy objects and release memory, and their name matches the class name preceded by a tilde. They do not take arguments or return values.
This document discusses constructors and destructors in C++. It defines a constructor as a special member function with the same name as the class that is used to initialize objects. Constructors are called automatically when objects are created and allow objects to be initialized before use. Constructors cannot be inherited or static and default and copy constructors are generated by the compiler. The document also discusses declaration, default arguments, copy constructors, and the order of constructor invocation.
The document discusses Python objects and types. It covers key concepts like object-oriented programming in Python, classes and instances, namespaces, scoping, and exception handling. Some main points include:
- Everything in Python is an object with an identity, type, and value. Objects live in dynamic namespaces and can be accessed via names.
- Classes are type objects that act as templates for creating instances when called. Instances are objects with the same methods and attributes as its class.
- Namespaces are where names are mapped to objects. Python has module, class, and instance namespaces that follow LEGB scoping rules.
- Exceptions are class objects that inherit from the built-in Exception class. The raise statement is used
C functions can be defined separately from objects, require function prototypes, and always pass parameters by copy rather than by reference. Function definitions specify the return type, name, and parameter list. Parameters are local variables within the function. Global variables can be accessed across files using extern declarations. Variables have block-level scope defined by curly braces. Header files contain common function prototypes and declarations to share across files.
C functions can be defined separately from objects, require function prototypes, and always pass parameters by copy rather than by reference. Function definitions specify the return type, name, and parameter list. Parameters are local variables initialized by copying the argument values. To modify arguments, pointers must be used. Header files contain common function prototypes and declarations to allow separate compilation. Scope rules determine where variables and functions can be accessed. Macros allow text substitution before compilation. Optional parameters are indicated by an ellipsis and accessed using stdarg.h functions.
- C functions are stand-alone entities that are not part of objects. They can be defined separately and loaded as needed.
- Function prototypes must appear in any file where functions are used to describe the function signature. Parameters are always passed by copy.
- Optional parameters in C functions are specified using an ellipsis (...) after required parameters. The stdarg.h header contains functions to access optional parameters within the function body.
Constructors initialize objects of a class when they are created. They are special member functions with the same name as the class. Destructors destroy objects and free allocated memory when objects go out of scope. Constructors can be default, parameterized, or copy constructors to initialize objects with different values. Destructors are used to clean up memory allocated by constructors.
The document discusses the Objective-C preprocessor and underlying C language features. It covers preprocessor directives like #define, #import, #include, and #undef. It also discusses arrays, structures, pointers, functions, and how Objective-C works with C at a low level. Blocks in Objective-C are described as being similar to functions but having some differences like needing to be declared in .m files instead of .h headers.
This document discusses object oriented programming concepts in C++ including string handling, copy constructors, polymorphism, and dynamic memory allocation. It provides examples of:
1) Using string class functions like append(), find(), length(), replace(), and swap() as well as string operators like =, +, +=, ==, <, and >.
2) Defining and using a copy constructor to initialize an object using another object of the same class.
3) Compile-time polymorphism through function and operator overloading allowing functions or operators to work with multiple types.
4) Dynamic memory allocation using new and delete to allocate and free memory for objects at runtime rather than compile-time.
The document provides information on various C++ concepts related to object oriented programming including:
- Data encapsulation and abstraction which involve wrapping data and functions together into classes and hiding implementation details.
- Inheritance which allows classes to inherit attributes and behaviors from other classes to promote code reuse.
- Polymorphism which allows classes to have different implementations of the same methods.
- Constructors and destructors which are special methods used to initialize and clean up objects.
- Composition and aggregation which describe relationships where a class contains other class objects.
Constructors and destructors play an important role in object-oriented programming. Constructors are special member functions that are called when objects are created. There are different types of constructors including parameterized, default, copy, conversion, and move constructors. Destructors are the inverse of constructors and are called when objects are destroyed. Destructors follow the same name convention as the class but with a tilde. Constructors and destructors are useful in real-time applications such as real-time locating systems and data transmission where they help properly allocate and release resources during an object's lifetime.
Constructors and destructors play an important role in object-oriented programming. Constructors are special member functions that are called when objects are created. There are different types of constructors including parameterized, default, copy, conversion, and move constructors. Destructors are the inverse of constructors and are called when objects are destroyed. Destructors follow the same name convention as the class but with a tilde. Constructors and destructors are useful in real-time applications such as real-time locating systems and data transmission where they help properly allocate and release resources during an object's lifetime.
The document discusses constructors, destructors, copy constructors and operator overloading in C++ classes. It provides examples of:
1) Defining a constructor for the rectangle class that initializes its data members.
2) Calling the constructor when creating new rectangle objects.
3) Defining a destructor for the string class that deletes the dynamically allocated string member.
4) Defining a copy constructor for the string class that makes a deep copy of the string member.
5) Overloading operators like << and >> as non-member functions to allow I/O for user-defined classes.
C++ Object oriented concepts & programmingnirajmandaliya
This document discusses various C++ concepts related to functions and operators. It defines what a default pointer is and how it receives addresses passed to a called function. It also discusses reference variables, inline functions, friend functions, default arguments, passing objects as parameters, function overloading, static members, function pointers, and operator overloading. It provides examples and explanations for each concept.
This document discusses constructors and destructors in C++. It explains that constructors initialize objects when they are created and prevent data members from having garbage values, while destructors destroy objects before they go out of scope. The document covers parameterized and copy constructors, constructor overloading, default constructor arguments, and how constructors and destructors are automatically called by the compiler. It also discusses dynamically initializing data members using constructors with pointer arguments.
The document discusses the system development life cycle (SDLC), which describes the stages of an information system development project. It outlines the typical stages: recognition of need, feasibility study, analysis, design, implementation, post-implementation, maintenance, and prototyping. The feasibility study assesses the economic, technical, and behavioral factors. Analysis involves gathering requirements through tools like interviews and documentation. Design defines technical specifications and system flow. Implementation deploys the system. Prototyping allows refining the system through iterative testing and user feedback before final implementation.
The document discusses the process of system design, which goes through logical and physical design phases. Logical design involves data flow diagrams and defining user needs, while physical design specifies design details for programmers. Structured design uses tools like data flow diagrams, data dictionaries, and structure charts to decompose the system into modules. A key part of design is structured walkthroughs where peers review and provide feedback on the design. User involvement is also important throughout the design process.
The document discusses various aspects of input design and computer output design. It describes how to design forms, including using rules and captions to guide the user, using boxes and spacing requirements. It also covers selecting appropriate paper for forms based on how many times it will be handled, folded, and environmental exposure. The overall goal is to make data entry and computer output as easy, logical and free from errors as possible for users.
The document discusses different methods of organizing computer files, including heap files, sequential files, indexed-sequential files, inverted list files, and direct files. It provides details on each method, such as how records are stored and accessed, their advantages and disadvantages, and examples. Key aspects covered include unordered storage in heap files, ordered storage and efficient sequential access in sequential files, indexed access for both sequential and random access in indexed-sequential files, and direct calculation of record locations in direct files.
The document discusses cost-benefit analysis, which involves identifying and categorizing the costs and benefits of projects or systems. It describes several methods for evaluating costs and benefits, including net benefit analysis, present value analysis, net present value, payback analysis, break-even analysis, and cash flow analysis. These methods are used to compare alternatives and determine which option provides the greatest value. The document provides examples and outlines the advantages and disadvantages of each evaluation method.
The document discusses key concepts in database design including fields, records, database management systems (DBMS), normalization, and the roles of a database administrator. It explains that a field is the smallest unit of data, a record contains related fields, and a DBMS provides an interface between data files and programs. The document also covers database normalization forms, logical and physical views of data, and functions of a DBMS like ensuring data integrity and security.
CASE tools automate and support various phases of the systems development life cycle. They include upper-CASE tools that support early phases, lower-CASE tools that support later phases, and I-CASE tools that support the entire SDLC. CASE tools improve software quality by reducing errors, improving designs, standardizing tasks, and providing automated functions. While acquisition and training costs of CASE tools are high, their use generally increases development productivity and quality.
The document discusses cost-benefit analysis and various methods used to evaluate costs and benefits of projects. It defines key terms like tangible/intangible and direct/indirect costs and benefits. Several evaluation methods are described - net benefit analysis, present value analysis, net present value, payback period analysis, break-even analysis and cash flow analysis. Their formulas, examples and advantages/disadvantages are provided. The document concludes that cost-benefit analysis involves identifying, categorizing and evaluating costs and benefits to interpret results and take action regarding alternative systems.
Data flow diagrams (DFDs) are a graphical tool used to communicate system requirements and analyze system logic. DFDs focus on the flow of data between external entities, processes, and data stores. They provide an overview of what data a system processes, what transformations are performed, what data is stored, and what results are produced. DFDs contain four main elements - external entities, data flows, processes, and data stores. External entities represent sources or destinations of data outside the system, processes represent actions performed on the data, data flows show the movement of data between elements, and data stores represent data repositories. DFDs can be decomposed into multiple levels to show increasing detail.
The document discusses the relationship between logical and physical design in system analysis and design, noting that the logical design defines system functions and components while the physical design implements the specific system, and that IPO/HIPO charts can be used to understand a system's structure and functions in a hierarchical manner by correlating its input, processing, and output steps.
This document contains 17 programming problems and their solutions involving object oriented programming concepts like classes, objects, functions, arrays, pointers etc. The problems cover basic concepts like calculating factorial, checking prime number, Fibonacci series, arithmetic operations using menus, finding largest element in array. More advanced concepts covered are bubble sort, selection sort, function overloading to calculate area of shapes, complex number addition using friend functions, student record management using classes. Overall, the document aims to provide practice on common OOP concepts through solving different programming problems.
Geothermal energy is renewable because the Earth continually generates heat from radioactive decay and residual heat from its formation. As long as the Earth is active geologically, it will continue producing heat that can be tapped into as a renewable energy source through technologies like geothermal power plants. The heat source is replenished naturally so geothermal energy is considered renewable.
Geothermal energy is renewable because the Earth continually generates heat from radioactive decay and residual heat from its formation. As long as the Earth is active geologically, it will continue producing heat that can be tapped into as a renewable energy source through technologies like geothermal power plants. The heat source is replenished naturally so geothermal energy is considered renewable.
Energy left over from the original formation of the planet along with heat from radioactive decay slowly escapes from within the Earth every day. In some areas where the increase in temperature with depth is high enough, this geothermal energy can be used to generate electricity, but is limited to only a few locations worldwide and faces technical challenges. Another form of geothermal energy is using the Earth's relatively constant subsurface temperature via heat pumps for heating and cooling buildings, which can reduce other energy needs for temperature regulation but cannot produce electricity.
Energy left over from the original formation of the planet along with heat from radioactive decay slowly escapes from within the Earth every day. In some areas where the increase in temperature with depth is high enough, this geothermal energy can be used to generate electricity, but is limited to only a few locations worldwide and faces technical challenges. Another form of geothermal energy is using the Earth's relatively constant subsurface temperature via heat pumps for heating and cooling buildings, which can reduce other energy needs for temperature regulation but cannot produce electricity.
This document discusses several issues related to human population growth and its impact on the environment. It notes that the global population will likely exceed 7 billion by 2015 and meeting the needs of this many people will be difficult without degrading natural resources and environmental quality. Rapid population growth in recent decades has contributed significantly to environmental problems. Other issues discussed include variations in population growth rates among countries, links between poverty, health and the environment, climate change impacts on health, and the importance of equitable distribution of resources.
This document discusses the relational model and relational database concepts. It covers domains and relations, relational keys like primary keys, candidate keys, foreign keys and their rules. It also discusses relational operators, relational algebra, relational calculus, and the SQL language. Key types like alternate keys, candidate keys, compound keys, primary keys, superkeys, and foreign keys are defined. Relational algebra operations like selection, projection, renaming, union, intersection, difference, cartesian product, and join are explained. Tuple relational calculus and domain relational calculus are introduced. Examples of queries using relational algebra and calculus are provided. Components of SQL like DDL, DML, DCL are listed
This document discusses different concepts related to the relational model including domains and relations, relational data integrity, keys such as primary keys, candidate keys, foreign keys and their rules. It also discusses relational operators, relational algebra, relational calculus and SQL. Finally, it describes different types of relational algebra operations including unary operations like select, project and rename and binary operations like join, union, intersection, difference and cartesian product.
This document discusses the relational model and relational database concepts. It covers domains and relations, relational keys like primary keys, foreign keys, and candidate keys. It also discusses relational algebra operations like selection, projection, join, and set operations. Relational calculus is introduced. The SQL language components of DDL, DML, and DCL are mentioned for data definition, manipulation, and control. Key concepts like views, nested tables, and correlated subqueries are also summarized briefly.
This document provides an introduction to object oriented programming concepts in C++. It covers key topics such as classes, objects, data members, methods, inheritance, constructors, destructors, static variables, function overloading, access specifiers, and abstract classes. The document contains 31 multiple choice questions to test understanding of these fundamental OOP concepts when programming in C++.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/how-axelera-ai-uses-digital-compute-in-memory-to-deliver-fast-and-energy-efficient-computer-vision-a-presentation-from-axelera-ai/
Bram Verhoef, Head of Machine Learning at Axelera AI, presents the “How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-efficient Computer Vision” tutorial at the May 2024 Embedded Vision Summit.
As artificial intelligence inference transitions from cloud environments to edge locations, computer vision applications achieve heightened responsiveness, reliability and privacy. This migration, however, introduces the challenge of operating within the stringent confines of resource constraints typical at the edge, including small form factors, low energy budgets and diminished memory and computational capacities. Axelera AI addresses these challenges through an innovative approach of performing digital computations within memory itself. This technique facilitates the realization of high-performance, energy-efficient and cost-effective computer vision capabilities at the thin and thick edge, extending the frontier of what is achievable with current technologies.
In this presentation, Verhoef unveils his company’s pioneering chip technology and demonstrates its capacity to deliver exceptional frames-per-second performance across a range of standard computer vision networks typical of applications in security, surveillance and the industrial sector. This shows that advanced computer vision can be accessible and efficient, even at the very edge of our technological ecosystem.
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfChart Kalyan
A Mix Chart displays historical data of numbers in a graphical or tabular form. The Kalyan Rajdhani Mix Chart specifically shows the results of a sequence of numbers over different periods.
The Microsoft 365 Migration Tutorial For Beginner.pptxoperationspcvita
This presentation will help you understand the power of Microsoft 365. However, we have mentioned every productivity app included in Office 365. Additionally, we have suggested the migration situation related to Office 365 and how we can help you.
You can also read: https://www.systoolsgroup.com/updates/office-365-tenant-to-tenant-migration-step-by-step-complete-guide/
Introduction of Cybersecurity with OSS at Code Europe 2024Hiroshi SHIBATA
I develop the Ruby programming language, RubyGems, and Bundler, which are package managers for Ruby. Today, I will introduce how to enhance the security of your application using open-source software (OSS) examples from Ruby and RubyGems.
The first topic is CVE (Common Vulnerabilities and Exposures). I have published CVEs many times. But what exactly is a CVE? I'll provide a basic understanding of CVEs and explain how to detect and handle vulnerabilities in OSS.
Next, let's discuss package managers. Package managers play a critical role in the OSS ecosystem. I'll explain how to manage library dependencies in your application.
I'll share insights into how the Ruby and RubyGems core team works to keep our ecosystem safe. By the end of this talk, you'll have a better understanding of how to safeguard your code.
In the realm of cybersecurity, offensive security practices act as a critical shield. By simulating real-world attacks in a controlled environment, these techniques expose vulnerabilities before malicious actors can exploit them. This proactive approach allows manufacturers to identify and fix weaknesses, significantly enhancing system security.
This presentation delves into the development of a system designed to mimic Galileo's Open Service signal using software-defined radio (SDR) technology. We'll begin with a foundational overview of both Global Navigation Satellite Systems (GNSS) and the intricacies of digital signal processing.
The presentation culminates in a live demonstration. We'll showcase the manipulation of Galileo's Open Service pilot signal, simulating an attack on various software and hardware systems. This practical demonstration serves to highlight the potential consequences of unaddressed vulnerabilities, emphasizing the importance of offensive security practices in safeguarding critical infrastructure.
Dandelion Hashtable: beyond billion requests per second on a commodity serverAntonios Katsarakis
This slide deck presents DLHT, a concurrent in-memory hashtable. Despite efforts to optimize hashtables, that go as far as sacrificing core functionality, state-of-the-art designs still incur multiple memory accesses per request and block request processing in three cases. First, most hashtables block while waiting for data to be retrieved from memory. Second, open-addressing designs, which represent the current state-of-the-art, either cannot free index slots on deletes or must block all requests to do so. Third, index resizes block every request until all objects are copied to the new index. Defying folklore wisdom, DLHT forgoes open-addressing and adopts a fully-featured and memory-aware closed-addressing design based on bounded cache-line-chaining. This design offers lock-free index operations and deletes that free slots instantly, (2) completes most requests with a single memory access, (3) utilizes software prefetching to hide memory latencies, and (4) employs a novel non-blocking and parallel resizing. In a commodity server and a memory-resident workload, DLHT surpasses 1.6B requests per second and provides 3.5x (12x) the throughput of the state-of-the-art closed-addressing (open-addressing) resizable hashtable on Gets (Deletes).
5th LF Energy Power Grid Model Meet-up SlidesDanBrown980551
5th Power Grid Model Meet-up
It is with great pleasure that we extend to you an invitation to the 5th Power Grid Model Meet-up, scheduled for 6th June 2024. This event will adopt a hybrid format, allowing participants to join us either through an online Mircosoft Teams session or in person at TU/e located at Den Dolech 2, Eindhoven, Netherlands. The meet-up will be hosted by Eindhoven University of Technology (TU/e), a research university specializing in engineering science & technology.
Power Grid Model
The global energy transition is placing new and unprecedented demands on Distribution System Operators (DSOs). Alongside upgrades to grid capacity, processes such as digitization, capacity optimization, and congestion management are becoming vital for delivering reliable services.
Power Grid Model is an open source project from Linux Foundation Energy and provides a calculation engine that is increasingly essential for DSOs. It offers a standards-based foundation enabling real-time power systems analysis, simulations of electrical power grids, and sophisticated what-if analysis. In addition, it enables in-depth studies and analysis of the electrical power grid’s behavior and performance. This comprehensive model incorporates essential factors such as power generation capacity, electrical losses, voltage levels, power flows, and system stability.
Power Grid Model is currently being applied in a wide variety of use cases, including grid planning, expansion, reliability, and congestion studies. It can also help in analyzing the impact of renewable energy integration, assessing the effects of disturbances or faults, and developing strategies for grid control and optimization.
What to expect
For the upcoming meetup we are organizing, we have an exciting lineup of activities planned:
-Insightful presentations covering two practical applications of the Power Grid Model.
-An update on the latest advancements in Power Grid -Model technology during the first and second quarters of 2024.
-An interactive brainstorming session to discuss and propose new feature requests.
-An opportunity to connect with fellow Power Grid Model enthusiasts and users.
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving
Manufacturing custom quality metal nameplates and badges involves several standard operations. Processes include sheet prep, lithography, screening, coating, punch press and inspection. All decoration is completed in the flat sheet with adhesive and tooling operations following. The possibilities for creating unique durable nameplates are endless. How will you create your brand identity? We can help!
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...Jason Yip
The typical problem in product engineering is not bad strategy, so much as “no strategy”. This leads to confusion, lack of motivation, and incoherent action. The next time you look for a strategy and find an empty space, instead of waiting for it to be filled, I will show you how to fill it in yourself. If you’re wrong, it forces a correction. If you’re right, it helps create focus. I’ll share how I’ve approached this in the past, both what works and lessons for what didn’t work so well.
Ivanti’s Patch Tuesday breakdown goes beyond patching your applications and brings you the intelligence and guidance needed to prioritize where to focus your attention first. Catch early analysis on our Ivanti blog, then join industry expert Chris Goettl for the Patch Tuesday Webinar Event. There we’ll do a deep dive into each of the bulletins and give guidance on the risks associated with the newly-identified vulnerabilities.
Have you ever been confused by the myriad of choices offered by AWS for hosting a website or an API?
Lambda, Elastic Beanstalk, Lightsail, Amplify, S3 (and more!) can each host websites + APIs. But which one should we choose?
Which one is cheapest? Which one is fastest? Which one will scale to meet our needs?
Join me in this session as we dive into each AWS hosting service to determine which one is best for your scenario and explain why!
Programming Foundation Models with DSPy - Meetup SlidesZilliz
Prompting language models is hard, while programming language models is easy. In this talk, I will discuss the state-of-the-art framework DSPy for programming foundation models with its powerful optimizers and runtime constraint system.
Fueling AI with Great Data with Airbyte WebinarZilliz
This talk will focus on how to collect data from a variety of sources, leveraging this data for RAG and other GenAI use cases, and finally charting your course to productionalization.
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
1. Course Name- B Sc IT
Subject Name - C++
Semester - II
Neetu Gupta
1
2. Contents
• Copy constructorFriend functions
• References data members
• Pointer data members
• Call by value
• Call by reference
3. Contents
• Function Template Definition
• Function Template Instantiation
• Class Template Definition
• Class Template Instantiation
• Non-type Parameters
• Class Template Specialization
• Class Template Members
• Class Template Friends
• Derived Class Templates
4. Copy Constructor
Copy constructor is
• a constructor function with the same name as the class
• used to make deep copy of objects.
• If a copy constructor is not defined in a class, the
compiler itself defines one. This will ensure a shallow
copy. If the class does not have pointer variables with
dynamically allocated memory, then one need not worry
about defining a copy constructor. It can be left to the
compiler's discretion.
• But if the class has pointer variables and has some
dynamic memory allocations, then it is a must to have a
copy constructor.
5. There are 3 important places where a copy
constructor is called.
• When an object is created from another
object of the same type
A a1;
A a2 = a1;
• When an object is passed by value as a
parameter to a function
• When an object is returned from a function
6. • For any class, the syntax for copy constructor
will be like
class-name (const class-name &b)
5. Name of copy constructor is same as class
name like any other constructor
6. The argument is of the class type itself.
7. The argument must be sent by reference
8. The argument must be sent as a constant
value
7. class B //With copy constructor
{
private:
char *name;
public:
B()
{
name = new char[20];
}
~B()
{
delete name[];
}
//Copy constructor
B (const B &b)
{
name = new char[20];
strcpy (name, b.name);
}
};
8. • Let us Imagine if you don't have a copy
constructor for the class B.
• At the first place, if an object is created from
some existing object, we cannot be sure that the
memory is allocated.
• Also, if the memory is deleted in destructor, the
delete operator might be called twice for the
same memory location. This is a major risk.
• One happy thing is, if the class is not so complex
this will come to the fore during development
itself. But if the class is very complicated, then
these kind of errors will be difficult to track.
9. • We can make use of this in a main() function as
main() {
B b1;
B b2 = b1;
}
• Here, b2 is created from object b1 with the call of copy
constructor.
• Hence the memory allocated to variable name will be
different for both the objects as we are doing so in copy
constructor
• If we have not done so, then both the objects b1 and b2
would be pointing to same memory location which might
lead to disasters in the program.
10. References
• C++ references allow you to create a second
name for the a variable that you can use to read
or modify the original data stored in that variable.
• This means that when you declare a reference
and assign it a variable, it will allow you to treat
the reference exactly as though it were the
original variable for the purpose of accessing
and modifying the value of the original variable--
even if the second name (the reference) is
located within a different scope. (important)
11. • This means, for instance, that if you make
your function arguments references, and
you will effectively have a way to change
the original data passed into the function.
• It allows you to dramatically reduce the
amount of copying that takes place behind
the scenes, when we pass a argument by
value in a function
12. Reference - Syntax
• Declaring a variable as a reference rather than a normal
variable simply entails appending an ampersand to the
type name, such as this "reference to an int"
int& foo = <variable-name>;
• When a reference is created, you must tell it which
variable it will become an alias for or store the reference
of.
• After you create the reference foo, whenever you use the
variable, you can just treat it as though it were a regular
integer variable. But when you create it, you must
initialize it with another variable, whose address it will
keep around behind the scenes to allow you to use it to
modify that variable.
13. • In a way, this is similar to having a pointer that
always points to the same thing.
• One key difference is that references do not
require dereferencing in the same way that
pointers do; you just treat them as normal
variables.
• A second difference is that when you create a
reference to a variable, you need not do
anything special to get the memory address. The
compiler figures this out for you
14. • A simple code could be as
int x;
// foo is now a reference to x
int& foo = x;
// foo and x are same so
// if you change foo, it will set x to 56
foo = 56;
cout << x <<endl;
Here output will be
56
15. Functions taking References
Parameters
• A parameter that we specify in function
declaration can be a reference too.
• That means when we change the value of
reference in the function, the value of
actual argument will also get changed.
• This we call as pass-by-refrence. An
important feature of C++.
16. • Here's a simple example of setting up a function
to take an argument "by reference",
implementing the swap function:
void swap (int& first, int& second) {
int temp = first;
first = second;
second = temp;
}
• Here first and second are passed by reference.
When we change the value of first and second
then the changes will be reflected in the original
arguments also.
17. int main () {
int a = 2;
int b = 3;
swap( a, b ); // call to swap function
return 0;
}
• After the call of swap function a will be 3 and b will be 2.
• Because a is passed to first and b is passed to second
in function swap.
• Both are references. When we change first and second
in swap, a and b are also changed.
18. References as class members
• You can store members by reference if they are
guaranteed to exist elsewhere.
• Reference member variables are used when the
object they refer to exists outside of the scope of
the class in question, and the same one is
guaranteed to exist for the duration of the
lifetime of your class' objects.
• A reference to the original is passed in as a
parameter to the constructor and the reference
member is initialized in the constructor's
initialization list.
19. class A {
}
class B {
public:
A& a; // Reference to class type A
int x;
B(A& extr)
:a(extr)
{
}
};
Here B is a class which has
one member variable a which is reference of type class A
second member variable, a normal variable of int type.
20. void main() {
A ref;
B b(ref) ;
b.x=9;
}
Here we create an object ref of type A.
• We send it to constructor of B, where it gets
initialized to a member of class B.
• Since a is reference, the objects ref and a are
pointing to same object and not to two different
objects.
21. Initializing reference members
• As we have already studied that a
reference should always be initialized with
a variable when it is declared.
• Hence, if we have a member variable
declared as reference it must be initialized
in the initialization list always otherwise
compiler will give an error.
22. //
class B {
public:
A& a; // Reference to class type A
int x;
B(A& extr)
:a(extr) // initialized in initialization list
{
a = extr; // compiler Error;
}
};
• If we try to assign a value to a reference in the constructor it will an error, as
shown above.
• Because giving reference a value in constructor is assignment not
initialization.
• It should always be done in the initialization list.
23. Pointers as data members
• Like normal variables, we can always have data
members which are pointers to a data type.
class A {
int* iptr;
}
• Here, the iptr is a pointer to int and not a simple
int type variable.
• We should take special care when we have
pointer data members
24. • A pointer data member should be properly
allocated and deallocated memory in the
constructor and destructor of the class.
• Every class that has a pointer data
member should include the following
member functions:
– a destructor,
– a copy constructor,
– operator= (assignment)
25. • Lets take an example
class Test //With copy constructor
{
private:
char *name;
public:
Test()
{
name = new char[20];
}
~ Test()
{
delete name[];
}
};
26. • Class test, has a data member name
which is a pointer to char type.
• We must be careful to alocate memory in
constructor for this using new operator.
• Similarly when the object is destroyed,
destructor will be called. We should be
careful to deallocate the memory that is
allocated in constructor using delete
operator.
27. Call by value vs. call by reference
• When we write a function like
f ( int x ) {
cout >> “ value of X in f() before change : “ >> x;
x =3;
cout >> “ value of X in f() before change : “ >> x;
}
Here x is passed by value that means if we change
the value of x in f(), there will be no effect on the
value of argument that is sent at the time of f()
call.
This is called as pass-by-value
28. • If we call function f() in main as
main() {
int i =10;
cout >> “ value of I before calling f() : “ >> I;
f(i);
cout >> “ value of I after calling f() : “ >> I;
}
Output will be :
value of I before calling f() : 10
value of X in f() before change : 10
value of X in f() before change : 3
value of I after calling f() : 10
29. • The value of i is set to 10 that is what is printed.
• When we pass I to f(), its value is set to X so X is
10.
• Later we change X to 3, that is what is printed.
• The control comes back to main after calling f(),
the I is still 10.
• Though we changed the value of parameter X in
f(), but the changes are not reflected in i.
• This is because X is passed by value.
30. • Pass by reference
When we write a function like
f ( int& x ) {
cout >> “ value of X in f() before change : “ >> x;
x =3;
cout >> “ value of X in f() before change : “ >> x;
}
• Here x is passed by reference and not by value
that means if we change the value of x in f(),
there will be change in the value of argument
that is sent at the time of f() call. This is called as
pass-by-reference
31. • If we call function f() in main as
main() {
int i =10;
cout >> “ value of I before calling f() : “ >> I;
f(i);
cout >> “ value of I after calling f() : “ >> I;
}
Output will be :
value of I before calling f() : 10
value of X in f() before change : 10
value of X in f() before change : 3
value of I after calling f() : 3
32. • The value of i is set to 10 that is what is printed.
• When we pass I to f(), its value is set to X so X is
10.
• Later we change X to 3, that is what is printed.
• The control comes back to main after calling f(),
the I is 3 now.
• We changed the value of parameter X in f(), the
changes are now reflected in i.
• This is because X is passed by reference.
33. Templates
• Templates are used to write down
generaic code.
• When we need to write a common code
for different data type basic or class type
we can do so with the help of templates.
• In c++, we will study 2 types
1. Function templates
2. class templates
34. Function Templates
• Function templates are special functions that
can operate with generic types.
• This allows us to create a function template
whose functionality can be adapted to more than
one type or class without repeating the entire
code for each type.
• In C++ this can be achieved using template
parameters.
35. Template parameter
• A template parameter is a special kind of parameter that
can be used to pass a type as argument.
• As regular function parameters can be used to pass
values to a function, template parameters allow to pass
also types to a function.
• These function templates can use these parameters as if
they were any other regular type to write a code for
generic data type or class.
36. Function template syntax
• The format for declaring function templates with
type parameters is:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
• The only difference between both prototypes is
the use of either the keyword class or the
keyword typename.
• Its use is indistinct, since both expressions have
exactly the same meaning and behave exactly
the same way.
37. • For example, to create a template function that returns
the greater one of two objects we could use:
template <class myType>
myType GetMax (myType a, myType b)
{
return (a>b?a:b);
}
• Here we have created a template function with myType
as its template parameter.
• This template parameter represents a type that has not
yet been specified, but that can be used in the template
function as if it were a regular type.
• As you can see, the function template GetMax returns
the greater of two parameters of this still-undefined type.
38. Function template - Use
• To use this function template we use the
following format for the function call:
function_name <type> (parameters);
• For example, to call GetMax to compare two
integer values of type int we can write:
int x,y;
GetMax <int> (x,y);
39. • When the compiler encounters this call to a
template function like,
GetMax <int> (x,y);
it uses the template to automatically generate a
function replacing each appearance of myType
by the type passed as the actual template
parameter (int in this case) and then calls it.
• This process is automatically performed by the
compiler and is invisible to the programmer.
40. // function template
#include <iostream>
using namespace std;
template <class T>
T GetMax (T a, T b) {
T result;
result = (a>b)? a : b;
return (result);
}
int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax<int>(i,j); // create a function for int type
n=GetMax<long>(l,m); // create a function for long type
cout << k << endl;
cout << n << endl;
return 0;
}
Output is
6
10
41. • In this case, we have used T as the template parameter
name instead of myType because it is shorter and in fact
is a very common template parameter name.
• In the example above we used the function template
GetMax() twice.
• The first time with arguments of type int and the second
one with arguments of type long.
• The compiler has instantiated and then called each time
the appropriate version of the function.
42. • As you can see, the type T is used within
the GetMax() template function even to
declare new objects of that type:
T result;
• Therefore, result will be an object of the
same type as the parameters a and b
when the function template is instantiated
with a specific type.
43. • Our template function includes only one
template parameter (class T) and the function
template itself accepts two parameters, both of
this T type.
• We cannot call our function template with two
objects of different types as arguments:
int i; long l; k = GetMax (i,l);
• This would not be correct, since our GetMax
function template expects two arguments of the
same type, and in this call to it we use objects of
two different types.
44. More than one type parameter
• We can also define function templates that accept more
than one type parameter, simply by specifying more
template parameters between the angle brackets.
• For example:
template <class T, class U>
T GetMin (T a, U b) {
return (a<b ? a :b);
}
In this case, our function template GetMin() accepts two
parameters of different types and returns an object of the
same type as the first parameter (T) that is passed.
45. • For example, after that declaration we
could call GetMin() with:
int I, j;
long l;
i = GetMin<int, long> (j, l);
or simply:
i = GetMin (j, l);
Here even though j and l have different
types, since the compiler can determine
the appropriate instantiation anyway.
46. Class Template
• We also have the possibility to write class templates, so that a class
can have members that use template parameters as types.
• For example
template <class T>
class mypair {
T values [2];
public:
mypair (T first, T second) {
values[0]=first;
values[1]=second;
}
};
47. Class Template definition
• We can define a class Template as
For example
template <class T>
class mypair {
T values [2];
public:
mypair (T first, T second) {
values[0]=first;
values[1]=second;
}
};
• The class that we have just defined serves to store two elements of any
valid type.
48. • For example, if we wanted to declare an object
of this class to store two integer values of type
int with the values 115 and 36 we would write:
mypair<int> myobject (115, 36);
• The same class would also be used to create an
object to store any other type:
mypair<double> myfloats (3.0, 2.18);
49. • The only member function in the previous
class template has been defined inline
within the class declaration itself.
• In case that we define a function member
outside the declaration of the class
template, we must always precede that
definition with the template <...> prefix as:
template <class T>
T mypair<T>::getmax ()
50. // class templates
#include <iostream>
using namespace std;
template <class T>
class mypair {
private:
T a, b;
public:
mypair (T first, T second) {
a=first; b=second;
}
T getmax ();
};
template <class T>
T mypair<T>::getmax () {
T retval;
retval = a>b? a : b;
return retval;
}
51. • In the example, mypair is the class that
stores two template type variables.
• It also has a function getMax(), that find
out the maximum of two numbers the
object of class stores.
52. Class Template Instantiation
• The compiler will generate the complete code of
the class for each type, when we declare an
object of the class myPair specifying a type of T.
• For example
int main () {
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}
• In this example, a complete class is created with T as int,
because we are using mypair <int>. This we can call
instantiation of class template.
53. Template specialization
• At times we want to define a different
implementation for a template when a
specific type is passed as template
parameter
• We can always declare a specialization of
that template for that particular data type
as the need be.
54. • This is the syntax used in the class template
specialization:
template <>
class mycontainer <char>
{
...
};
• Notice that we precede the class template name with an
empty template<> parameter list. This is to explicitly
declare it as a template specialization.
55. • For example, let's suppose that we have a very
simple class called mycontainer that can have
the members as
• one element of any type and
• it has just one member function called increase,
which increases its value.
• But we find that when it stores an element of type
char it would be more convenient to have a
completely different implementation with a function
member uppercase,
• so we decide to declare a class template
specialization for type char only.
56. // template specialization
#include <iostream>
using namespace std;
// class template:
template <class T>
class mycontainer {
T element;
public:
mycontainer (T arg) {
element=arg;
}
T increase () {
return ++element;
}
};
57. // class template specialization for char type will be as:
template <>
class mycontainer <char> {
char element;
public:
mycontainer (char arg) {
element=arg;
}
char uppercase () {
if ((element>='a')&&(element<='z'))
element+='A'-'a';
return element;
}
};
58. Carefully see the code used
template <>
• This is to explicitly declare it as a template
specialization.
class mycontainer <char> {
...
};
• Here <char> is the specialization parameter after
the class template name. This specialization
parameter itself identifies the type for which we
are going to declare a template class
specialization i.e. char.
59. • Notice the differences between the generic class
template and the specialization:
template <class T> class mycontainer { ... };
template <> class mycontainer <char> { ... };
Here
first line is the generic template,
second one is the template specialization.
Remember
• When we declare specializations for a template class, we
must also define all its members, even those exactly
equal to the generic template class, because there is no
"inheritance" of members from the generic template to
the specialization.
60. Non-type parameters for
templates
•Besides the template arguments that are
preceded by the class or typename keywords ,
which represent types, templates can also have
regular typed parameters, similar to those
found in functions.
Like we can a particular type specified like int,
float, or any class-type as well as
template <class T, int N>
Here T is template type where as second
parameter is fixed i.e. int here.
60
61. // sequence template
// this class template that is used to contain sequences of elements
#include <iostream>
using namespace std;
template <class T, int N>
class mysequence {
T memblock [N];
public:
void setmember (int x, T value);
T getmember (int x);
};
template <class T, int N>
void mysequence<T,N>::setmember (int x, T value) {
memblock[x]=value;
}
template <class T, int N>
T mysequence<T,N>::getmember (int x) {
return memblock[x];
}
61
62. •In the class mysequence we have two arguments
for template;
first is template typename that will vary when we
create an object of this class
second is specific i.e. int and when we create an
object we will use this as
mysequence <double, 5> mydoubles;
double replaces T
5 is the value for parameter N
62
64. It is also possible to set default values or types for class template
parameters.
For example, if the previous class template definition had been:
template <class T=char, int N=10>
class mysequence {..
};
We could create objects using the default template parameters by
declaring:
mysequence<> myseq;
This would be same as
mysequence<char,10> myseq
64
65. Default values for class template
parameters
• It is also possible to set default values or types for class template
parameters.
For example, if the previous class template definition had been:
template <class T=char, int N=10>
class mysequence {..
};
We could create objects using the default template parameters by declaring:
mysequence<> myseq;
This would be same as
mysequence<char,10> myseq
66. Friends functions
• In principle, private and protected
members of a class cannot be accessed
from outside the same class in which they
are declared.
• However, this rule does not affect friends.
• Friends are functions or classes declared
with the friend keyword.
67. • we can declare an external function as
friend of a class
• This allows this function to have access
to the private and protected members of
this class.
• For this
• We should declare a prototype of this
external function within the class,
• and preceding it with the keyword friend
68. • Suppose we want to declare an external
function in our program, that create a copy
of CRectangle class.
• This function should be like
CRectangle duplicate (CRectangle rectparam) {
CRectangle rectres;
rectres.width = rectparam.width*2;
rectres.height = rectparam.height*2;
return (rectres);
}
• But if we define this function outside class, we can not access width
and height members of class CRectangle here as they are protected
or private.
• For this we declare this function as friend to class CRectangle
69. // friend functions
#include <iostream>
using namespace std;
class CRectangle {
int width, height;
public:
void set_values (int, int);
int area () {
return (width * height);
}
friend CRectangle duplicate (CRectangle); // friend function declaration in class
};
void CRectangle::set_values (int a, int b) {
width = a; height = b;
}
CRectangle duplicate (CRectangle rectparam) {
CRectangle rectres;
rectres.width = rectparam.width*2;
rectres.height = rectparam.height*2;
return (rectres);
}
70. • It can be used as
int main () {
CRectangle rect, rectb;
rect.set_values (2,3);
rectb = duplicate (rect);
cout << rectb.area();
return 0;
}
• The duplicate function is a friend of CRectangle. From
within that function we have been able to access the
members width and height of different objects of type
CRectangle, which are private members.
• Notice that neither in the declaration of duplicate() nor in
its later use in main() have we considered duplicate a
member of class CRectangle.
71. Friend classes
• As we have the possibility to define a
friend function, we can also define a class
as friend of another class
• We can do so by granting that first class
access to the protected and private
members of the second class.
• This can be done by declaring first class
as a friend of other class.
72. Friend class - syntax
• We can do this as
class A {
public:
friend class B;
}
• Here class B is friend of class A that
means class B can access the all private
and protected members of class A.
73. Example:
• Suppose we want to have declared CRectangle
as a friend of CSquare so that CRectangle
member functions could have access to the
protected and private members of CSquare,
more concretely to CSquare::side, which
describes the side width of the square.
• This is necessary because within the declaration
of CRectangle we want to add a function
convert() that will change an object of type
CSquare to CRectangle.
74. // friend class #include <iostream>
using namespace std;
class CSquare;
class CRectangle {
private :
int width, height;
public:
int area () {return (width * height);}
void convert (CSquare a);
};
class CSquare {
private:
int side;
public:
void set_side (int a) {side=a;}
friend class CRectangle; // declares CRectangle as the friend class of CSquare
};
void CRectangle::convert (CSquare a) {
width = a.side; // accessing private member of CSquare class
height = a.side;
}
75. • Now we can easily covert a CSquare class into
CRectangle as
int main () {
CSquare sqr;
CRectangle rect;
sqr.set_side(4);
rect.convert(sqr); // conversion
cout << rect.area();
return 0;
}
Output is:
16