Introduction to C++
Difference between C and C++
Evolution of C++
Procedure Oriented Programming vs Object OrientedProgramming
Key concepts of Object-Oriented Programming
Advantages and Disadvantages of OOP
Oop lec 2(introduction to object oriented technology)Asfand Hassan
The document discusses high-level and low-level programming languages. It explains that high-level languages resemble human languages but must be translated into machine language that CPUs can understand using compilers. Low-level languages like assembly language are closer to machine language. The document also introduces object-oriented programming characteristics like encapsulation, inheritance and polymorphism. It provides examples of classes and objects in C++ and describes relationships between objects like attributes, associations and aggregations.
This document provides an overview of the C++ programming language for beginners. It discusses C++ history and how it compares to C as a superset. Key features of C++ include object-oriented programming, efficiency, portability, and use of pointers. The document outlines the development environment of NetBeans IDE and principles of software quality like security, efficiency, reliability and maintainability. It introduces object-oriented programming concepts and shows the syntax for defining functions and using C code in C++. The document is a tutorial that covers various aspects of the C++ language for learning purposes.
C++ is an object-oriented programming language that is an extension of C. It allows for data abstraction through the use of classes and objects. Some key features of C++ include data encapsulation, inheritance, polymorphism, and reusability. C++ is a mid-level language that is compiled, supports pointers, and has a rich standard library. It is commonly used for system applications, games, and other performance-critical software due to its speed and ability to interface with hardware. Some example applications include operating systems, browsers, databases, and graphics/game engines.
This document provides an overview of object-oriented programming concepts using C++. It discusses C++ as an improvement over C that allows both object-oriented and procedural programming. The keys sections define objects, encapsulation, polymorphism, inheritance and classes. It also discusses defining classes in C++, objects and encapsulation, messages and polymorphism, data abstraction and natural building blocks of OOP. Later sections provide examples of polymorphism in applications and programs.
This document provides an overview of object-oriented concepts and C++ programming. It discusses procedural programming, structured programming, and object-oriented programming approaches. It describes the key characteristics of OOP including modularity, abstraction, encapsulation, inheritance, polymorphism, and dynamic binding. The document also discusses the history and characteristics of the C++ programming language, and covers C++ tokens, identifiers, keywords, and constants.
This document provides an overview of the topics covered in the CS6301 Programming and Data Structures II course. The course is divided into 5 units:
Unit I covers object-oriented programming fundamentals in C++, including classes, objects, encapsulation, inheritance, and polymorphism.
Unit II focuses on advanced OOP concepts like string handling, copy constructors, and exception handling.
Unit III discusses templates, STL containers, iterators, and file handling in C++.
Unit IV presents advanced non-linear data structures like AVL trees, splay trees, and heaps.
Unit V examines graph algorithms like breadth-first search, depth-first search, minimum spanning
OOP Unit 1 - Foundation of Object- Oriented Programmingdkpawar
Foundation of object oriented programing-
Introduction to procedural, modular, object-oriented and generic programming techniques
Limitations of procedural programming
Need of object-oriented programming
fundamentals of object-oriented programming:
objects, classes, data members, methods, messages, data encapsulation, data abstraction and information hiding, inheritance, polymorphism.
Inline functions
Function overloading
call by value and call by reference, return by reference,
Introduction to C++
Difference between C and C++
Evolution of C++
Procedure Oriented Programming vs Object OrientedProgramming
Key concepts of Object-Oriented Programming
Advantages and Disadvantages of OOP
Oop lec 2(introduction to object oriented technology)Asfand Hassan
The document discusses high-level and low-level programming languages. It explains that high-level languages resemble human languages but must be translated into machine language that CPUs can understand using compilers. Low-level languages like assembly language are closer to machine language. The document also introduces object-oriented programming characteristics like encapsulation, inheritance and polymorphism. It provides examples of classes and objects in C++ and describes relationships between objects like attributes, associations and aggregations.
This document provides an overview of the C++ programming language for beginners. It discusses C++ history and how it compares to C as a superset. Key features of C++ include object-oriented programming, efficiency, portability, and use of pointers. The document outlines the development environment of NetBeans IDE and principles of software quality like security, efficiency, reliability and maintainability. It introduces object-oriented programming concepts and shows the syntax for defining functions and using C code in C++. The document is a tutorial that covers various aspects of the C++ language for learning purposes.
C++ is an object-oriented programming language that is an extension of C. It allows for data abstraction through the use of classes and objects. Some key features of C++ include data encapsulation, inheritance, polymorphism, and reusability. C++ is a mid-level language that is compiled, supports pointers, and has a rich standard library. It is commonly used for system applications, games, and other performance-critical software due to its speed and ability to interface with hardware. Some example applications include operating systems, browsers, databases, and graphics/game engines.
This document provides an overview of object-oriented programming concepts using C++. It discusses C++ as an improvement over C that allows both object-oriented and procedural programming. The keys sections define objects, encapsulation, polymorphism, inheritance and classes. It also discusses defining classes in C++, objects and encapsulation, messages and polymorphism, data abstraction and natural building blocks of OOP. Later sections provide examples of polymorphism in applications and programs.
This document provides an overview of object-oriented concepts and C++ programming. It discusses procedural programming, structured programming, and object-oriented programming approaches. It describes the key characteristics of OOP including modularity, abstraction, encapsulation, inheritance, polymorphism, and dynamic binding. The document also discusses the history and characteristics of the C++ programming language, and covers C++ tokens, identifiers, keywords, and constants.
This document provides an overview of the topics covered in the CS6301 Programming and Data Structures II course. The course is divided into 5 units:
Unit I covers object-oriented programming fundamentals in C++, including classes, objects, encapsulation, inheritance, and polymorphism.
Unit II focuses on advanced OOP concepts like string handling, copy constructors, and exception handling.
Unit III discusses templates, STL containers, iterators, and file handling in C++.
Unit IV presents advanced non-linear data structures like AVL trees, splay trees, and heaps.
Unit V examines graph algorithms like breadth-first search, depth-first search, minimum spanning
OOP Unit 1 - Foundation of Object- Oriented Programmingdkpawar
Foundation of object oriented programing-
Introduction to procedural, modular, object-oriented and generic programming techniques
Limitations of procedural programming
Need of object-oriented programming
fundamentals of object-oriented programming:
objects, classes, data members, methods, messages, data encapsulation, data abstraction and information hiding, inheritance, polymorphism.
Inline functions
Function overloading
call by value and call by reference, return by reference,
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX
Most C++ compilers don't care what extension you give your source code, but if you don't specify otherwise, many will use .cpp by default
Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have respective Operating Systems.
Object oriented programming 7 first steps in oop using c++Vaibhav Khanna
Advantages of C++
Portability. C++ offers the feature of portability or platform independence which allows the user to run the same program on different operating systems or interfaces at ease. ...
Object-oriented. ...
Multi-paradigm. ...
Low-level Manipulation. ...
Memory Management. ...
Large Community Support. ...
Compatibility with C. ...
Scalability.
This document is a lecture on programming fundamentals that discusses what a programming language is, innovations in programming like object-oriented programming and the Unified Modeling Language, and the history and basics of C and C++. It provides examples of a simple "Hello World" C++ program and explains each part of the code.
Introduction to C++ : Object Oriented Technology, Advantages of OOP, Input- output in
C++, Tokens, Keywords, Identifiers, Data Types C++, Derives data types. The void data
type, Type Modifiers, Typecasting, Constant
Unit 1 of c++ part 1 basic introductionAKR Education
This document provides an overview and introduction to C++ programming. It discusses that C++ is an object-oriented programming language created in 1983 as an extension of C. It allows programmers to write low-level and high-level code and supports features like abstraction, encapsulation, inheritance and polymorphism. The document also discusses compilers for C++ on different operating systems and the differences between C and C++ programming.
C++ session 1 introduces object oriented programming concepts including objects, classes, data encapsulation, inheritance, polymorphism, dynamic binding, and message passing. Objects are the basic building blocks and are members of classes. Classes define user-defined data types that contain both code and data. Data encapsulation combines data and functions into a single unit called a class. Inheritance allows classes to inherit features from other classes without modifying them. Polymorphism allows functions to take on multiple forms based on argument types. Dynamic binding determines which code to run at runtime. Message passing involves sending requests to objects to execute procedures.
This document provides an overview of an introductory course on object-oriented programming concepts and C++. The course aims to help participants understand the importance of OOP and basic OOP terminology. The document outlines the course objectives, flow, and modules which include programming paradigms, OOP concepts, classes and objects, inheritance, polymorphism and functions in C++. It also provides examples and explanations of key OOP concepts such as abstraction, encapsulation, inheritance and polymorphism.
C++ is known to be a very powerful language. C++ allow you to have a lot of control as to how you use computer resources so, in the right hand its speed and ability to cheaply use resources should be able to surpass other language. thanks to C++'s performance.
1. Object oriented programming (OOP) is a programming paradigm that models concepts as "objects" that contain data and functionality.
2. A class defines the format for objects, including attributes like properties and behaviors like methods. Creating an object from a class is like a real-world object.
3. OOP concepts like encapsulation, inheritance, and polymorphism address limitations of procedural programming by combining related data and functions into classes and objects. Encapsulation wraps data and functions together, hiding implementation details.
Object Oriented Programming is a programming paradigm that uses objects and their interactions to design applications and computer programs. The document discusses the limitations of procedural programming and how object oriented programming aims to address these. It introduces key concepts of OOP like classes, objects, encapsulation, inheritance and polymorphism. Classes act as a blueprint to create real objects with data and behaviors. The document provides examples of defining empty classes and creating multiple objects in Python.
This document provides information about a class on Object Oriented Programming (OOP) with C++ taught by Venkatadri.M, an Assistant Professor at the University of Petroleum and Energy Studies in Dehradun, India. The class covers the evolution of OOP, the history of C++, organizing data and functions in OOP, features of object oriented languages, and polymorphism. The instructor uses diagrams, animations and PowerPoint presentations to teach the concepts and address frequently asked questions from students.
This document provides an overview of object-oriented programming (OOP) and C++. It discusses key concepts in OOP like classes, objects, inheritance, polymorphism and encapsulation. It then covers the history and development of OOP languages, with Simula 67 being an early language. C++ is presented as building on C with object-oriented features. The document defines common C++ elements like data types, operators, streams and functions. It provides examples of C++ programs and concepts like structures, call by reference, and function overloading.
This document provides an overview of object-oriented programming (OOP) concepts, including:
- It compares procedural programming (POP) and OOP, noting that OOP was developed to overcome limitations of POP like reusability and maintainability.
- In OOP, a program is divided into objects that contain both data and functions, whereas in POP programs are divided into smaller programs called functions.
- The document outlines some key differences between POP and OOP, such as OOP emphasizing data over procedures and using access specifiers and bottom-up design.
The document discusses several programming paradigms including structured programming, procedural programming, abstract data types (ADTs), and object-oriented programming (OOP). It provides details on key concepts for each paradigm such as encapsulation, inheritance, and polymorphism. C++ and C# are presented as examples of languages that support the OOP paradigm.
This document discusses object-oriented programming (OOP) concepts and languages. It begins with an introduction to programming languages from low-level machine languages to high-level languages. It then covers OOP concepts like classes, objects, encapsulation, inheritance, and polymorphism. It provides examples to illustrate these concepts. The document also discusses advantages and disadvantages of OOP as well as its suitability for complex, modular systems that can benefit from code reuse.
This whole C++ course focus on giving the insight of different kind of data structures that could be used while dealing with a variety of data that needs to be stored depending upon the circumstances.
The course also focus on how to reduce the complexity of a code by teaching us the variety of approaches that could be employed for a solving the same problem.
The document discusses object-oriented programming concepts in C++ including classes, objects, encapsulation, inheritance, polymorphism, and more. It provides examples of class definitions and accessing class members. Key points covered include:
- Classes are templates that define objects, while objects are instances of classes.
- Encapsulation involves wrapping data and functions together in a class. Inheritance allows classes to acquire properties from other classes.
- Polymorphism allows a method to perform different actions based on parameters. Message passing involves communication between objects.
- Structured programming divides a program into functions and data, while object-oriented programming divides it into objects that contain data and functions.
1) Object oriented databases were developed to directly represent complex objects from emerging applications that could not be effectively modeled in the relational model. 2) Embedded SQL allows SQL queries to be embedded within a general purpose programming language to access and manipulate database objects. 3) Object oriented database management systems can be either pure object oriented programming languages with persistence or extend relational databases with object oriented features as defined in the SQL3 standard.
The document provides an introduction to C++ programming and the Visual Studio IDE. It discusses key C++ concepts like headers, namespaces, I/O operators, and sample programs. It also covers setting up and debugging projects in Visual Studio, including adding breakpoints and stepping through code. The lab session aims to familiarize students with C++ programming and Visual Studio to lay the foundation for object-oriented concepts covered in subsequent labs.
An In-Depth Exploration of Natural Language Processing: Evolution, Applicatio...DharmaBanothu
Natural language processing (NLP) has
recently garnered significant interest for the
computational representation and analysis of human
language. Its applications span multiple domains such
as machine translation, email spam detection,
information extraction, summarization, healthcare,
and question answering. This paper first delineates
four phases by examining various levels of NLP and
components of Natural Language Generation,
followed by a review of the history and progression of
NLP. Subsequently, we delve into the current state of
the art by presenting diverse NLP applications,
contemporary trends, and challenges. Finally, we
discuss some available datasets, models, and
evaluation metrics in NLP.
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX
Most C++ compilers don't care what extension you give your source code, but if you don't specify otherwise, many will use .cpp by default
Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have respective Operating Systems.
Object oriented programming 7 first steps in oop using c++Vaibhav Khanna
Advantages of C++
Portability. C++ offers the feature of portability or platform independence which allows the user to run the same program on different operating systems or interfaces at ease. ...
Object-oriented. ...
Multi-paradigm. ...
Low-level Manipulation. ...
Memory Management. ...
Large Community Support. ...
Compatibility with C. ...
Scalability.
This document is a lecture on programming fundamentals that discusses what a programming language is, innovations in programming like object-oriented programming and the Unified Modeling Language, and the history and basics of C and C++. It provides examples of a simple "Hello World" C++ program and explains each part of the code.
Introduction to C++ : Object Oriented Technology, Advantages of OOP, Input- output in
C++, Tokens, Keywords, Identifiers, Data Types C++, Derives data types. The void data
type, Type Modifiers, Typecasting, Constant
Unit 1 of c++ part 1 basic introductionAKR Education
This document provides an overview and introduction to C++ programming. It discusses that C++ is an object-oriented programming language created in 1983 as an extension of C. It allows programmers to write low-level and high-level code and supports features like abstraction, encapsulation, inheritance and polymorphism. The document also discusses compilers for C++ on different operating systems and the differences between C and C++ programming.
C++ session 1 introduces object oriented programming concepts including objects, classes, data encapsulation, inheritance, polymorphism, dynamic binding, and message passing. Objects are the basic building blocks and are members of classes. Classes define user-defined data types that contain both code and data. Data encapsulation combines data and functions into a single unit called a class. Inheritance allows classes to inherit features from other classes without modifying them. Polymorphism allows functions to take on multiple forms based on argument types. Dynamic binding determines which code to run at runtime. Message passing involves sending requests to objects to execute procedures.
This document provides an overview of an introductory course on object-oriented programming concepts and C++. The course aims to help participants understand the importance of OOP and basic OOP terminology. The document outlines the course objectives, flow, and modules which include programming paradigms, OOP concepts, classes and objects, inheritance, polymorphism and functions in C++. It also provides examples and explanations of key OOP concepts such as abstraction, encapsulation, inheritance and polymorphism.
C++ is known to be a very powerful language. C++ allow you to have a lot of control as to how you use computer resources so, in the right hand its speed and ability to cheaply use resources should be able to surpass other language. thanks to C++'s performance.
1. Object oriented programming (OOP) is a programming paradigm that models concepts as "objects" that contain data and functionality.
2. A class defines the format for objects, including attributes like properties and behaviors like methods. Creating an object from a class is like a real-world object.
3. OOP concepts like encapsulation, inheritance, and polymorphism address limitations of procedural programming by combining related data and functions into classes and objects. Encapsulation wraps data and functions together, hiding implementation details.
Object Oriented Programming is a programming paradigm that uses objects and their interactions to design applications and computer programs. The document discusses the limitations of procedural programming and how object oriented programming aims to address these. It introduces key concepts of OOP like classes, objects, encapsulation, inheritance and polymorphism. Classes act as a blueprint to create real objects with data and behaviors. The document provides examples of defining empty classes and creating multiple objects in Python.
This document provides information about a class on Object Oriented Programming (OOP) with C++ taught by Venkatadri.M, an Assistant Professor at the University of Petroleum and Energy Studies in Dehradun, India. The class covers the evolution of OOP, the history of C++, organizing data and functions in OOP, features of object oriented languages, and polymorphism. The instructor uses diagrams, animations and PowerPoint presentations to teach the concepts and address frequently asked questions from students.
This document provides an overview of object-oriented programming (OOP) and C++. It discusses key concepts in OOP like classes, objects, inheritance, polymorphism and encapsulation. It then covers the history and development of OOP languages, with Simula 67 being an early language. C++ is presented as building on C with object-oriented features. The document defines common C++ elements like data types, operators, streams and functions. It provides examples of C++ programs and concepts like structures, call by reference, and function overloading.
This document provides an overview of object-oriented programming (OOP) concepts, including:
- It compares procedural programming (POP) and OOP, noting that OOP was developed to overcome limitations of POP like reusability and maintainability.
- In OOP, a program is divided into objects that contain both data and functions, whereas in POP programs are divided into smaller programs called functions.
- The document outlines some key differences between POP and OOP, such as OOP emphasizing data over procedures and using access specifiers and bottom-up design.
The document discusses several programming paradigms including structured programming, procedural programming, abstract data types (ADTs), and object-oriented programming (OOP). It provides details on key concepts for each paradigm such as encapsulation, inheritance, and polymorphism. C++ and C# are presented as examples of languages that support the OOP paradigm.
This document discusses object-oriented programming (OOP) concepts and languages. It begins with an introduction to programming languages from low-level machine languages to high-level languages. It then covers OOP concepts like classes, objects, encapsulation, inheritance, and polymorphism. It provides examples to illustrate these concepts. The document also discusses advantages and disadvantages of OOP as well as its suitability for complex, modular systems that can benefit from code reuse.
This whole C++ course focus on giving the insight of different kind of data structures that could be used while dealing with a variety of data that needs to be stored depending upon the circumstances.
The course also focus on how to reduce the complexity of a code by teaching us the variety of approaches that could be employed for a solving the same problem.
The document discusses object-oriented programming concepts in C++ including classes, objects, encapsulation, inheritance, polymorphism, and more. It provides examples of class definitions and accessing class members. Key points covered include:
- Classes are templates that define objects, while objects are instances of classes.
- Encapsulation involves wrapping data and functions together in a class. Inheritance allows classes to acquire properties from other classes.
- Polymorphism allows a method to perform different actions based on parameters. Message passing involves communication between objects.
- Structured programming divides a program into functions and data, while object-oriented programming divides it into objects that contain data and functions.
1) Object oriented databases were developed to directly represent complex objects from emerging applications that could not be effectively modeled in the relational model. 2) Embedded SQL allows SQL queries to be embedded within a general purpose programming language to access and manipulate database objects. 3) Object oriented database management systems can be either pure object oriented programming languages with persistence or extend relational databases with object oriented features as defined in the SQL3 standard.
The document provides an introduction to C++ programming and the Visual Studio IDE. It discusses key C++ concepts like headers, namespaces, I/O operators, and sample programs. It also covers setting up and debugging projects in Visual Studio, including adding breakpoints and stepping through code. The lab session aims to familiarize students with C++ programming and Visual Studio to lay the foundation for object-oriented concepts covered in subsequent labs.
Similar to Object Oriented Programming using C++ - OOPS concepts using C++ programming language (20)
An In-Depth Exploration of Natural Language Processing: Evolution, Applicatio...DharmaBanothu
Natural language processing (NLP) has
recently garnered significant interest for the
computational representation and analysis of human
language. Its applications span multiple domains such
as machine translation, email spam detection,
information extraction, summarization, healthcare,
and question answering. This paper first delineates
four phases by examining various levels of NLP and
components of Natural Language Generation,
followed by a review of the history and progression of
NLP. Subsequently, we delve into the current state of
the art by presenting diverse NLP applications,
contemporary trends, and challenges. Finally, we
discuss some available datasets, models, and
evaluation metrics in NLP.
Data Communication and Computer Networks Management System Project Report.pdfKamal Acharya
Networking is a telecommunications network that allows computers to exchange data. In
computer networks, networked computing devices pass data to each other along data
connections. Data is transferred in the form of packets. The connections between nodes are
established using either cable media or wireless media.
This is an overview of my current metallic design and engineering knowledge base built up over my professional career and two MSc degrees : - MSc in Advanced Manufacturing Technology University of Portsmouth graduated 1st May 1998, and MSc in Aircraft Engineering Cranfield University graduated 8th June 2007.
Better Builder Magazine brings together premium product manufactures and leading builders to create better differentiated homes and buildings that use less energy, save water and reduce our impact on the environment. The magazine is published four times a year.
Sri Guru Hargobind Ji - Bandi Chor Guru.pdfBalvir Singh
Sri Guru Hargobind Ji (19 June 1595 - 3 March 1644) is revered as the Sixth Nanak.
• On 25 May 1606 Guru Arjan nominated his son Sri Hargobind Ji as his successor. Shortly
afterwards, Guru Arjan was arrested, tortured and killed by order of the Mogul Emperor
Jahangir.
• Guru Hargobind's succession ceremony took place on 24 June 1606. He was barely
eleven years old when he became 6th Guru.
• As ordered by Guru Arjan Dev Ji, he put on two swords, one indicated his spiritual
authority (PIRI) and the other, his temporal authority (MIRI). He thus for the first time
initiated military tradition in the Sikh faith to resist religious persecution, protect
people’s freedom and independence to practice religion by choice. He transformed
Sikhs to be Saints and Soldier.
• He had a long tenure as Guru, lasting 37 years, 9 months and 3 days
Cuttack Call Girls 💯Call Us 🔝 7374876321 🔝 💃 Independent Female Escort Service
Object Oriented Programming using C++ - OOPS concepts using C++ programming language
1. 20CSG01 - OBJECT ORIENTED
PROGRAMMING USING C++
1
SRI RAMAKRISHNA INSTITUTE OF TECHNOLOGY, COIMBATORE-10
(An Autonomous Institution)
Approved by AICTE, New Delhi – Affiliated to Anna University, Chennai)
(Accredited by NAAC with ‘A’ Grade and All UG Engineering Programmes are Accredited by NBA)
Department of Computer Science and Engineering
Object Oriented Programming using C++ - Preetha V AP/CSE
2. Outline
Fundamentals of OOP and C++
• Structural versus object-oriented Programming - Elements of object oriented
programming- benefits of OOP – Structure of C++ program - Variables - Tokens -
Keywords – Identifiers -Type modifiers - Type casting - Input and Output - Data
Types and Expressions - Operators - Flow of control - Arrays, Strings and
Pointers.
Classes and Objects
• Classes and Objects - Class specification: Class Members, Access Specifier, Scope
resolution operator- Class Instantiation - Accessing class members- Passing and
returning objects - Array of objects – Constructors: Parameterized constructors -
Default arguments – Copy Constructor - Constructor overloading, Destructors -
new, delete operators - “this” pointer - Friend classes and friend functions.
Object Oriented Programming using C++ - Preetha V AP/CSE 2
3. Programming Languages
• Programming languages allow programmers to code software.
• The three major families of languages are:
Machine languages
Assembly languages
High-Level languages
Object Oriented Programming using C++ - Preetha V AP/CSE 3
4. Machine Languages
• Comprised of 1s and 0s
• The “native” language of a computer
• Difficult to program – one misplaced 1 or 0 will cause the program to
fail.
• Example of code:
1110100010101 111010101110
10111010110100 10100011110111
Object Oriented Programming using C++ - Preetha V AP/CSE 4
5. Assembly Languages
• Assembly languages are a step towards easier programming.
• Assembly languages are comprised of a set of elemental commands
which are tied to a specific processor.
• Assembly language code needs to be translated to machine language
before the computer processes it.
• Example:
ADD 1001010, 1011010
Object Oriented Programming using C++ - Preetha V AP/CSE 5
6. High-Level Languages
• High-level languages represent a giant leap towards easier programming.
• The syntax of HL languages is similar to English.
• Historically, we divide HL languages into two groups:
Procedural languages
Object-Oriented languages (OOP)
Object Oriented Programming using C++ - Preetha V AP/CSE 6
7. Procedural Languages
• Early high-level languages are typically called procedural languages.
• Procedural languages are characterized by sequential sets of linear
commands. The focus of such languages is on structure.
• Examples include C, COBOL, Fortran, LISP, Perl, HTML, VBScript
Object Oriented Programming using C++ - Preetha V AP/CSE 7
8. TYPICAL STRUCTURE OF POP
Object Oriented Programming using C++ - Preetha V AP/CSE 8
9. Relationship of Data And Functions of POP
Object Oriented Programming using C++ - Preetha V AP/CSE 9
10. Object-Oriented Languages
• Most object-oriented languages are high-level languages.
• The focus of OOP languages is not on structure, but on modeling data.
• Programmers code using “blueprints” of data models called classes.
• Examples of OOP languages include C++, Visual Basic.NET and Java.
Object Oriented Programming using C++ - Preetha V AP/CSE 10
12. INTRODUCTION
• T Bells LAB early in 1980’s by BJARNE STROUSTRUP.
• STROUSTRUP added some features to his favorite language Simula
67. (Earliest OOP).
• STROUSTRUP called “ C with Classes ”.
• C++ ( C Plus Plus) is named by Rick Masitti.
Object Oriented Programming using C++ - Preetha V AP/CSE 12
13. Born
December 30, 1950 ) (age 60)
Aarhus, Denmark
Occupation
College of Engineering Chair in
Computer Science Professor, Texas
A&M University USA
Known for The creation of C++
BJARNE STROUSTRUP
Object Oriented Programming using C++ - Preetha V AP/CSE 13
14. Basic concepts of OOP
• Object based programming is a newer paradigm that implements some
features of object oriented programming but not all. In object based
programming, data and its associated meaningful functions are
enclosed in one single entity a class.
• Classes enforce information hiding and abstraction thereby separating
the implementation details and the uses interface.
Object Oriented Programming using C++ - Preetha V AP/CSE 14
15. Contd..
• Object - Objects have states and behaviors. Example: A Student has
states - color, name, as well as behaviors - reading, writing, eating. An
object is an instance of a class.
• Class - A class can be defined as a template/blueprint that describes
the behaviors/states that object of its type support.
• Methods/Member functions - A method is basically a behavior. A
class can contain many methods. It is in methods where the logics are
written, data is manipulated and all the actions are executed.
• Instance Variables/Data Members - Each object has its unique set of
instance variables. An object's state is created by the values assigned to
these instance variables.
Object Oriented Programming using C++ - Preetha V AP/CSE 15
16. Basic concepts of OOP
These general concepts of OOP are given below:
Data Abstraction
Data Encapsulation
Modularity
Inheritance
Polymorphism
Object Oriented Programming using C++ - Preetha V AP/CSE 16
17. Data Abstraction
• Abstraction refers to the act of representing essential features
without including the background details or explanations.
• Since the classes use the concept of data abstraction , they are known
as ADT(Abstract Data Types).
Object Oriented Programming using C++ - Preetha V AP/CSE 17
18. Data Encapsulation
• The wrapping up of data and operations / functions (that operate on the
data) into a single unit (called class) is known as Encapsulation.
• The data is not accessible to the outside world, and only those functions
which are wrapped in the class can access it.
• These functions provide the interface between the object’s data and the
program.
• The insulation of the data from direct access by the program is called
data hiding or information hiding.
Object Oriented Programming using C++ - Preetha V AP/CSE 18
20. What is a Modularity ?
• Modularity is the property of a system that has been
decomposed into a set of cohesive and loosely coupled
modules.
Object Oriented Programming using C++ - Preetha V AP/CSE 20
21. Modularity
The act of partitioning a program into individual components is
called modularity. The justification for partitioning a program is that
• it reduces its complexity to some degree and
• it creates a number of well-defined, documented boundaries
within the program
Object Oriented Programming using C++ - Preetha V AP/CSE 21
22. Inheritance
• Inheritance is the capability of one class of things to inherit capabilities or
properties from another class.
• Inheritance is the process by which objects of one class acquire the
properties of objects of another class.
• It supports the concept of hierarchical classification.
• In OOP, the concept of inheritance provides the idea of reusability.
Object Oriented Programming using C++ - Preetha V AP/CSE 22
24. Polymorphism
• Polymorphism is the ability for a message or data to be processed in
more than one form.
• The process of making an operator to exhibit different behaviours in
different instances is known as operator overloading.
• Using a single function name to perform different types of tasks is
known as function overloading.
Object Oriented Programming using C++ - Preetha V AP/CSE 24
26. Dynamic Binding
• Binding refers to the linking of a procedure call to the code to be
executed in response to the call.
• Dynamic binding(also known as late binding or run-time
binding) means that the code associated with a given procedure call
is not known until the time of the call at run-time.
• It is associated with polymorphism and inheritance.
Object Oriented Programming using C++ - Preetha V AP/CSE 26
27. Message Passing
• Message passing involves specifying the name of the object,the
name of the function(message) and the information to be sent.
Object Oriented Programming using C++ - Preetha V AP/CSE 27
28. Benefits of oops
• OOP offers several benefits to the program designer and the user.
• Object-orientation contributes to the solutions of many problem
associated with the development and quality of software products.
• The new technology promises greater programmer productivity, better
quality of software and lesser maintenance cost.
Object Oriented Programming using C++ - Preetha V AP/CSE 28
29. CONTD..
The principal advantages
• Through inheritance, we can eliminate redundant code and extend the use of
existing classes.
• We can built programs from standard working modules that communicate
with one another rather than, having to start writing the code from scratch.
• This leads to saving of development time and higher productivity.
• The principle of data hiding helps the programmers to built secure program
that can’t be invaded by code in other parts of the program.
• It is possible to have multiple objects to coexist without any interference.
• It is possible to map objects in the problem domain to those objects in the
program
Object Oriented Programming using C++ - Preetha V AP/CSE 29
30. ADVANTAGES of OOP
• Re-use of code.
• Ease of comprehension.
• Ease of fabrication and maintenance.
• Easy redesign and extension.
Object Oriented Programming using C++ - Preetha V AP/CSE 30
31. DISADVANTAGES of OOP
• With OOP, classes tend be overly generalized.
• The relations among classes become artificial at times.
• The OOP programs’ design is tricky.
• Also one need to do proper planning and proper design for
OOP programming.
• To program with OOP, programmer need proper skills such as
design skills, programming skills, thinking in terms of objects
etc.
Object Oriented Programming using C++ - Preetha V AP/CSE 31
32. C++ CHARACTER SET
• Letters:- A-Z, a-z
• Digits:- 0 to 9
• Special Symbols:- space + - / ( ) [ ] = ! = < > , ‘ “ $ # ; : ? &
• White Spaces:- Blank Space , Horizontal Tab, Vertical tab, Carriage
Return.
• Other Characters:- C++ can process any of the 256 ASCII Characters
as data or as literal.
Object Oriented Programming using C++ - Preetha V AP/CSE 32
33. TOKENS
• The Smallest individual unit in a program is known as Token.
• Lexical Unit is the another name given to Token.
• C++ has following Tokens
Keywords
Identifiers
Literals or Constants
Punctuators
Operators
Object Oriented Programming using C++ - Preetha V AP/CSE 33
34. KEY WORDS
• Key words are the words that convey special meaning to the compiler.
• Key words are also called as Reserved words meaning their meaning is
reserved in C++.
• Some of Key words are,
float int auto extern
double if else char
case do while goto…etc
• Added by ANSI C++
bool true false export
mutable typeid typename using
Object Oriented Programming using C++ - Preetha V AP/CSE 34
35. IDENTIFIERS
• Identifier refers to the name of variables, functions, arrays, classes,
etc. created by the programmer.
• Identifier is an arbitrary long sequence of letters and digits.
• The first character must be letter.
• The underscore ( _ ) counts as letter.
• Upper and Lower case letters are different.
• All characters are significant.
Object Oriented Programming using C++ - Preetha V AP/CSE 35
36. EXAMPLES OF IDENTIFIERS
• C++ is a Case Sensitive Language as it treats upper case letters and
lower case letters differently.
• Some Valid identifiers,
Myfile DATE9_7_8 z3t9x3
MYFILE _DS _FXR
• Some Invalid identifiers,
DATA-REC 28dre break
Object Oriented Programming using C++ - Preetha V AP/CSE 36
37. LITERALS
Literals often referred to as constants.
Constants refers to fixed values that do not change during the
execution of a program.
These are the data items that never change their value during the
program run.
Object Oriented Programming using C++ - Preetha V AP/CSE 37
38. TYPES OF C++ LITERALS
• INTEGER – CONSTANT
• CHARACTER – CONSTANT
• FLOATING – CONSTANT
• STRING – LITERAL
Object Oriented Programming using C++ - Preetha V AP/CSE 38
39. INTEGER CONSTANT
• These are the whole numbers without any fractional part.
• An integer constant must have at least one digit and must not contain
fractional part.
• It may contain + or - Sign.
• A number with no sign is assumed as positive.
• Commas can not appear in integer constant.
Object Oriented Programming using C++ - Preetha V AP/CSE 39
40. TYPES OF INTEGER CONSTANTS
• Decimal Integer Constants
• Octal Integer Constants
• Hexadecimal Constants
Object Oriented Programming using C++ - Preetha V AP/CSE 40
41. DECIMAL INTEGER CONSTANT
• An integer constant consisting of sequence of digits is taken to be
decimal integer constant unless it begins with 0.
• For instance 1234,56,+86,-56,-89,-22 are decimal integer constant.
Object Oriented Programming using C++ - Preetha V AP/CSE 41
42. OCTAL INTEGER CONSANT
• A sequence of digits starting with 0(digit Zero) is taken to be an octal
integer constant.
• for instance Decimal 8 is written as 010
as octal integer
8 10 =10 8
• Decimal 12 is written as
12 10 = 14 8
Object Oriented Programming using C++ - Preetha V AP/CSE 42
43. CHARACTER CONSTANT
• A character constant is one character enclosed within single quotes
Valid constants ‘a’ ‘z’ ‘k’
Invalid Constants a z k
• In c++ character constant must have single character and must be
enclosed in single quotes.
Object Oriented Programming using C++ - Preetha V AP/CSE 43
44. NONGRAPHIC CHARACTERS
Nongraphic character constants are those characters that can not be
typed directly from the keyboard.
e.g backspace, tab, carriage return
C++ Allows programmers to have certain nongraphic characters.
Object Oriented Programming using C++ - Preetha V AP/CSE 44
45. ESCAPE SEQUENCES
Escape sequences are nongraphic character constants these are also
called as non printing characters.
These nongraphic characters are represented by means of escape
sequence and is represented by a backslash ( ) followed by a one or
more character.
Object Oriented Programming using C++ - Preetha V AP/CSE 45
46. ESCAPE SEQUCENCE IN C++
Escape Sequence Non Graphic Character
a Bell
b Back Space
f Form Feed
n New Line
r Carriage Return
t Horizontal Tab
v Vertical Tab
’ Single Quote
” Double Quote
? Question Mark
on Octal Number ( On represents
the number in octal)
xHn Hexadecimal number
0 Null
Object Oriented Programming using C++ - Preetha V AP/CSE 46
47. NOTE
THESE ESCAPE SQUENCES ARE USED IN OUTPUT STATEMENT COUT
FOR EX:
cout<<“nt Wel Come”; // Right statement
cin>>”nt”>>n; //Wrong statement
Do not use in cin statements
Object Oriented Programming using C++ - Preetha V AP/CSE 47
48. FLOATING CONSTANTS
Floating constants are also called as Real constants. These may be
written in one of two of forms called fractional form or exponent
form.
A real constant in fractional form must have one digit before a
decimal point and at least one digit after the decimal point. It may
also have either +ve or –ve sign preceding it. A real constant with no
sign is assumed to be positive.
Object Oriented Programming using C++ - Preetha V AP/CSE 48
49. EXAMPLES OF REAL CONSTANTS
The following are the valid real constants in fractional form.
2.0 17.5 -89.9 -0.000732
The following are the invalid real constants in fractional
7 7. 24.34.32
12,45,344.09
Object Oriented Programming using C++ - Preetha V AP/CSE 49
50. REAL CONSTANTS IN EXPONENT FORM
A Real constant in exponent form has two parts
1. Mantissa
2. Exponent
Mantissa must be either an integer or proper real constant. The
mantissa is followed by letter E or e and the exponent must be an
integer.
Object Oriented Programming using C++ - Preetha V AP/CSE 50
51. EXAMPLE OF REAL CONSTANTS
The floating point number 5.8 can be written as,
0.58 x 101=0.58E01 or 0.58e01, here E01 or e01 represents 101
0.58 E01
Mantissa part Exponent part
Valid Real Constants : 123E03, 0.76e02, -0.12e-2
Invalid Real Constants: 172.E03, 1.2E,0.4E2.3
Object Oriented Programming using C++ - Preetha V AP/CSE 51
52. STRING LITERAL
A String Literal is a sequence of characters surrounded by double
quotes
A Multi character constants are treated as string literals.
For Example: “abc” in the memory this string is represented as
“abc0” i.e along with the terminating character (Slash Zero).
String is an array of character.
Object Oriented Programming using C++ - Preetha V AP/CSE 52
53. PUNCTUATORS
Punctuators are also called as separators The Followings are used as
punctuators
Brackets [ ]
Parantheses ( )
Braces { }
Comma ,
Semicolon ;
Colon :
Asterisk *
Ellipsis …
Equal Sign =
Pound Sign #
Object Oriented Programming using C++ - Preetha V AP/CSE 53
54. OPERATORS
Operators are the foundation of any programming language.
Operators allows us to perform different kinds of operations on
operands.
Operators are tokens that triggers some computation when applied to
a variable and other objects in an function.
Object Oriented Programming using C++ - Preetha V AP/CSE 54
55. UNARY OPERATORS
Unary Operators are those operators they act upon one operand.
OR
Operators that require one operator to operate upon.
& Address Operator
* Indirection Operator
+ Unary Plus
- Unary Minus
~ Bitwise Compliment
++ Increment Operator
-- Decrement Operator
Object Oriented Programming using C++ - Preetha V AP/CSE 55
56. BINARY OPERATORS
• Binary Operators are those operators that require two
operands to operate upon.
Arithmetic Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder or Modulus
Object Oriented Programming using C++ - Preetha V AP/CSE 56
57. SHIFT OPERATORS
<< (Shift Left)
>> (Shift Right)
For More information you will study in future chapters.
Object Oriented Programming using C++ - Preetha V AP/CSE 57
58. LOGICAL OPERATORS
&& Logical AND
|| Logical OR
! Logical Negation
Object Oriented Programming using C++ - Preetha V AP/CSE 58
59. ASSIGNMENT OPERATORS
The assignment operator is used to store the constants, variables, and result
of an expression and return value of a function from right side into variable
placed in left side.
= Assignment Operator
When same variable is used in both left and right side of an arithmetic
expression, we can use the shortcut assignment operators .
The operators are : +=, – =, *=, /=, %=
*= Assign Product a*=b------------ a=a*b
/= Assign Quotient
%= Assign Remainder
+= Assign Sum
-= Assign Minus
Object Oriented Programming using C++ - Preetha V AP/CSE 59
60. Relational Operator
< Less than
> Greater than
<= Less than equal to
>= Greater than equal to
== Equal to
!= Not equal to
Object Oriented Programming using C++ - Preetha V AP/CSE 60
61. Other Operators
• Conditional operators: The ?: are conditional operators. They do the job done by
if..else control structure.
• Syntax : expression1 ? expression2 : expression3;
• Ex : big = (a>b) ? a : b;
• Sizeof and Comma operators: The sizeof operator returns the memory size
occupied by an operand in terms of bytes.
• Ex : a = sizeof(int);
• The comma operator (,) adjoins several expressions.
• Ex : x = (y = 3, y + 1);
Object Oriented Programming using C++ - Preetha V AP/CSE 61
62. Operators in C++
C++ introduces some new operators. They are :
<< insertion operator (or output operator)
>> extraction operator (or input operator)
:: Scope resolution operator
::* pointer-to-member declarator
->* pointer-to-member operator
.* pointer-to-member operator
delete memory release operator
endl line feed operator
new memory allocation operator
setw field width operator
Object Oriented Programming using C++ - Preetha V AP/CSE 62
65. Built-in- data type
• Primary (Fundamental) data types in C/C++ programming includes the 4 most basic data types,
that is:
• int: It is responsible for storing integers. The memory it occupies depends on the compiler (32
or 64 bit). In general, int data type occupies 4 bytes of memory when working with a 32-bit
compiler.
• float: It is responsible for storing fractions or digits up to 7 decimal places. It is usually referred
to as a single-precision floating-point type. It occupies 4 bytes of memory
• char: It can be used to store a set of all characters which may include alphabets, numbers and
special characters. It occupies 1 byte of memory being the smallest addressable unit of a
machine containing a fundamental character set.
• double: It is responsible for storing fractions or digits up to 15-16 decimal places. It is usually
referred to as a double-precision floating-point type. It occupies 8 bytes of memory
• void (Null) data type: It indicates zero or no return value. It is generally used to assign the null
value while declaring a function.
Object Oriented Programming using C++ - Preetha V AP/CSE 65
66. Built-in- data type
• In C++, in addition to the primary data types available in C, there are
few more data types available in the C++ programming language.They
are:
• bool: It refers to a boolean/logical value. It can either be true or false.
• wchar_t: It refers to a wide character whose size is either 2 or 4 bytes.
It is similar to the char data type but the only difference is the space
occupied in the computer memory.
• string: Instead of declaring an array of characters to enter a string
data type, C++ gives you the provision to declare the “string” data
type.
Object Oriented Programming using C++ - Preetha V AP/CSE 66
67. Derived Data Types
• Secondary (Derived) Data Types in C and C++
• As the name itself suggests, they are derived from the fundamental data
types in the form of a group to collect a cluster of data used as a single
unit. These include:
• Arrays: A collection of data items of similar data types, which is accessed
using a common name.
• The basic syntax of declaring an array is: return_type array_name[size];
• For instance: float marks[5];
• Pointers: Pointers in C/C++ are basically variables that are used to store the
memory address of another variable.
• Functions: It is a group of statements that are written to perform a specific
task. Functions are either user-defined or built-in library functions.
Object Oriented Programming using C++ - Preetha V AP/CSE 67
68. User-defined Data Types
• User-defined Data Types in C and C++
• Structures – It is a user-defined data type in which a collection of different
data types can be made and accessed through an object.
• Union– A special kind of data type which gives us the provision to store
different data types in the same memory location.
• Class- C++ also permits us to define another user-defined data type known
as class which can be used, just like any other basic data type, to declare
variables. The class variables are known as objects.
• Enumeration – It refers to the arithmetic data types used to define
variables to specify only certain discrete integer values throughout the
entire program.
Object Oriented Programming using C++ - Preetha V AP/CSE 68
69. Reference variables in C++
• When a variable is declared as reference, it becomes an alternative
name for an existing variable.
• A variable can be declared as reference by putting ‘&’ in the
declaration.
• The reference variable can be created as follows:
data-type & reference-name=variable-name;
• C++ assigns additional meaning to the symbol &. Here, & is not an
address operator.
Object Oriented Programming using C++ - Preetha V AP/CSE 69
71. #include<iostream>
using namespace std; //Using namespace std, tells the compiler to use standard namespace. Namespace
collects identifiers used for class, object and variables.
int main()
{
int x = 10;
// ref is a reference to x.
int &ref = x;
// Value of x is now changed to 20
ref = 20;
cout << "x = " << x << endl ;
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << endl ;
return 0;
}
Output:
x = 20
ref = 30
Object Oriented Programming using C++ - Preetha V AP/CSE 71
72. Type modifiers
• Modifiers basically alter the function of a data type and make it more specific by the inclusion of
additional provisions.
• C++ allows us to use some modifiers for int, char and double types
• signed
• unsigned
• long
• Short
• Signed: It is used to store zero, positive or negative values.(signed variable stores the signed value in the
allocated memory)
• Unsigned: It can store only zero or positive values.(unsigned variable does not store signed value)
• Long: It is used to store large integer numbers. The size of the long type is 8 bytes.
• Short: It is used to store small integer numbers. Its size is of 2 Bytes.
• short modifier makes a type to use less number of bytes and it reduces the range of values for that type.
Object Oriented Programming using C++ - Preetha V AP/CSE 72
73. Type modifiers
• long and short modify the maximum and minimum values that a data type will hold.
• A plain int must have a minimum size of short.
• Size hierarchy : short int < int < long int
• Size hierarchy for floating point numbers is : float < double < long double
• long float is not a legal type and there are no short floating point numbers.
• Signed types includes both positive and negative numbers.
• Unsigned, numbers are always without any sign, that is always positive.
Object Oriented Programming using C++ - Preetha V AP/CSE 73
74. Type modifiers
• The modifiers signed, unsigned, long, and short can be applied to integer base types. In
addition, signed and unsigned can be applied to char, and long can be applied to double.
• The modifiers signed and unsigned can also be used as prefix to long or short modifiers.
For example, unsigned long int.
• C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can
simply use the word unsigned, short, or long, without int. It automatically implies int.
• For example, the following two statements both declare unsigned integer variables.
unsigned x;
unsigned int y;
Object Oriented Programming using C++ - Preetha V AP/CSE 74
75. Type modifiers
Data Type / Size(in bytes) Range
short int / 2 -32,768 to 32,767
unsigned short int / 2 0 to 65,535
unsigned int / 4 0 to 4,294,967,295
int / 4 -2,147,483,648 to 2,147,483,647
long int / 4 -2,147,483,648 to 2,147,483,647
unsigned long int / 4 0 to 4,294,967,295
signed char / 1 -128 to 127
unsigned char / 1 0 to 255
float / 4
double / 8
long double / 12
wchar_t / 2 or 4 1 wide character
Object Oriented Programming using C++ - Preetha V AP/CSE 75
76. Type casting
• Converting an expression of a given type into another type is known as type-casting.
• Implicit conversion
• Implicit conversions do not require any operator. They are automatically performed when a value is
copied to a compatible type.
Eg: short a=2000;
int b;
b=a;
• Here, the value of a has been promoted from short to int and we have not had to specify any type-
casting operator. This is known as a standard conversion.
• Standard conversions affect fundamental data types, and allow conversions such as the conversions
between numerical types (short to int, int to float, double to int...), to or from bool, and some pointer
conversions.
• Some of these conversions may imply a loss of precision, which the compiler can signal with a
warning. This warning can be avoided with an explicit conversion.
Object Oriented Programming using C++ - Preetha V AP/CSE 76
77. Type casting
• Explicit conversion
Eg: short a=2000;
int b;
b=(int) a;
b= int (a);
• Two notations for explicit type conversion:
(1) Functional notation
(2) C-like casting notation
Object Oriented Programming using C++ - Preetha V AP/CSE 77
78. Inbuilt Typecasting Functions in C/C++
• There are 5 basic types of inbuilt typecast functions in C/C++:
• atof(): We use it to convert string data type into the float data type.
• atoi(): We use it to convert string data type into the int data type.
• atol(): We use it to convert string data type into the long data type.
• itoa(): We use it to convert int data type into the string data type.
• ltoa(): We use it to convert long data type into the string data type.
Object Oriented Programming using C++ - Preetha V AP/CSE 78
79. Control Statements
• Control statements are elements in the source code that control the
flow of program execution.
• They include blocks using { and } brackets, loops using for, while and
do while, and decision-making using if and switch.
• There are two types of control statements:
• conditional and
• unconditional.
Object Oriented Programming using C++ - Preetha V AP/CSE 79
80. Control Statements
• Conditional statements are executed when one or more conditions are satisfied.
• The most common of these conditional statements is the if statement.
• C++ uses many other conditional statements including:
• if-else: An if-else statement operates on an either/or basis. One statement is executed
if the condition is true; another is executed if the condition is false.
• if-else if-else: This statement chooses one of the statements available depending on
the condition. If no conditions are true, the else statement at the end is executed.
• while: While repeats a statement as long as a given statement is true.
• do while: A do while statement is similar to a while statement with the addition that
the condition is checked at the end.
• for: A for statement repeats a statement as long as the condition is satisfied.
Object Oriented Programming using C++ - Preetha V AP/CSE 80
81. Control Statements
• Unconditional control statements do not need to satisfy any condition. They
immediately move control from one part of the program to another part.
• Unconditional statements in C++ include:
• goto: A goto statement directs control to another part of the program.The goto
statement is used for transferring the control of a program to a given label. The
syntax of goto statement looks like this:
goto label_name;
• break: A break statement terminates a loop (a repeated structure)
• continue: Continue statement is used inside loops. Whenever a continue statement
is encountered inside a loop, control directly jumps to the beginning of the loop for
next iteration, skipping the execution of statements inside loop’s body for the
current iteration.
Object Oriented Programming using C++ - Preetha V AP/CSE 81
82. Control Statements
If statement
Syntax:
if(condition){
//code to be executed
}
If else statement
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Object Oriented Programming using C++ - Preetha V AP/CSE 82
83. Nested if statement
if(condition)
{
//code to be executed
}
else if(condition)
{//code to be executed
}
else if(condition)
{
//code to be executed
}
Else
{
//code to be executed
}
Object Oriented Programming using C++ - Preetha V AP/CSE 83
84. Switch Statements
syntax
switch (n)
{
case 1: // code to be executed if n = 1; break;
case 2: // code to be executed if n = 2; break;
default: // code to be executed if n doesn't match any cases
}
Object Oriented Programming using C++ - Preetha V AP/CSE 84
85. Input and output statements
• Input Stream: If the direction of flow of bytes is from device(for
example: Keyboard) to the main memory then this process is called
input.
• Output Stream: If the direction of flow of bytes is opposite, i.e. from
main memory to device( display screen ) then this process is called
output.
Object Oriented Programming using C++ - Preetha V AP/CSE 85
86. Header files available in C++ for Input / Output
operation
• iostream: iostream stands for standard input output stream. This
header file contains definitions to objects like cin, cout etc.
• iomanip: iomanip stands for input output manipulators. The
methods declared in this files are used for manipulating streams.
This file contains definitions of setw, setprecision etc.
• fstream: This header file mainly describes the file stream. This
header file is used to handle the data being read from a file as
input or data being written into the file as output.
Object Oriented Programming using C++ - Preetha V AP/CSE 86
87. Accessing Public Data Members
class Student
{
public:
int rollno;
string name;
};
int main()
{
Student A;
Student B;
A.rollno=1;
A.name="Adam";
B.rollno=2;
B.name="Bella";
cout <<"Name and Roll no of A is :"<< A.name << A.rollno;
cout <<"Name and Roll no of B is :"<< B.name << B.rollno; }
Object Oriented Programming using C++ - Preetha V AP/CSE 87
88. PREDEFINED STREAMS IN I/O LIBRARY
At the lowest level files are implemented as streams of bytes, then
What is STREAM?
A Stream is simply a sequence of bytes.
Input and output operations are supported by the istream (input
stream) and ostream (output stream) classes.
Object Oriented Programming using C++ - Preetha V AP/CSE 88
89. PREDEFINED STREAMS IN I/O LIBRARY
The ostream output operation, referred to as insertion and is
performed by insertion operator <<
The istream input operation, referred to as extraction and is
performed by extraction operator >>
Object Oriented Programming using C++ - Preetha V AP/CSE 89
90. EXTRACTION AND INSERTION SYMBOLS
extraction operator Symbol is,
>>
insertion operator symbol is,
<<
Object Oriented Programming using C++ - Preetha V AP/CSE 90
91. cin and cout statements
cin (pronounced as see-in) stands for console input.
cout (pronounced as see-out) stands for console output.
Object Oriented Programming using C++ - Preetha V AP/CSE 91
92. SYNTAX OF cin STATEMENT
The general format or the syntax of cin statement is,
cin>>variablename;
Or
cin>>variablename1>>variablename2>>variable name3………>>variablenamen;
for example if four variables are to be input form the keyboard then,
cin>>a>>b>>c>>d;
Or the same statement can be written as follows,
cin>>a;
cin>>b;
cin>>c;
cin>>d;
Object Oriented Programming using C++ - Preetha V AP/CSE 92
93. SYNTAX OF cout STATEMENT
• The general format or the syntax of cout statement is,
cout<<variablename;
Or
cout<<variablename1<<variablename2<<variable name3………<<variablenamen;
for example if four variables are to be input form the keyboard then,
cout<<a <<b <<c <<d;
Or the same statement can be written as follows,
cout<<a;
cout<<b;
cout<<c;
cout<<d;
Object Oriented Programming using C++ - Preetha V AP/CSE 93
94. cout STATEMENT
Another way of writing cout statement is,
cout<<string<<variablename;
where,
String is a sequence of characters enclosed within a double quotation.
Variable name is the value of variable which is to be printed after the
message(string)
Object Oriented Programming using C++ - Preetha V AP/CSE 94
95. cout STATEMENT
totalamt;=6700;
cout<<“The Total Amount is = “<<totalamt;
Here, in this example
The Total Amount is= is the string
And the totalamt is the variable name, the value of the total is printed
Out put of this statement is as follows
The total Amount is = 6700
Object Oriented Programming using C++ - Preetha V AP/CSE 95
96. cout STATEMENT
As studied escape sequences are used in out put (cout) statements
• cout<<“ntBasic Pay=“<<basic<<“nt DA=“<<da<<“nt HRA =
“<<hra<<“nt Gross Salary = “<<gs;
output of the above statement is,
Basic Pay=5900
DA=40
HRA =30
Gross Salary = 10030
Object Oriented Programming using C++ - Preetha V AP/CSE 96
97. COMMENTS
The comments are the non executable statements. When ever
compiler identifies this is comment then it ignores. There are two
types of comments in C++
Single Line Comment (//)
Multi Line Comment (starts with /* and ends with */)
Object Oriented Programming using C++ - Preetha V AP/CSE 97
98. COMMENTS
The comments are the non executable statements. When ever compiler
identifies this is comment then it ignores.
• Single Line Comment Example
// My First C++ Program
This is the comment. All lines beginning with // are the comments in
the program.
Starting with /* and ended with */ is used for multi line comments
• Multi Line Comment Example
/* Write a CPP Program that calculates the sum and average of three
numbers*/
Object Oriented Programming using C++ - Preetha V AP/CSE 98
99. I/O OPERATORS
Input coming from the user’s terminal referred to as standard input is
tied to the predefined iostream cin
output directed to the user’s terminal, referred to as standard
output, is tied to the predefined iostream cout.
Object Oriented Programming using C++ - Preetha V AP/CSE 99
100. OUTPUT OPERATOR “<<’’
The output operator (“<<’’) (“put to’’), also called as stream insertion
operator is used to direct a value to the standard output device.
For example
cout<<“The Sum of 5 + 2 = “;
cout<< 5 + 2 ;
The statement will produce following output
The Sum of 5 + 2 = 7
Object Oriented Programming using C++ - Preetha V AP/CSE 100
101. OUTPUT OPERATOR <<
Now observe the output of following statement.
cout<< “The Sum of 5 + 2 is “;
cout<< 5 + 2;
cout<<“n”;
cout<<“The Result pf 8 – 2 is“;
cout<<8 – 2 ;
The Output of abve set of statements will be as follows,
The Sum of 5 + 2 is 7
The Result pf 8 – 2 is 6
Object Oriented Programming using C++ - Preetha V AP/CSE 101
102. OUTPUT OPERATOR <<
The same statements can be written by using single cout statement
cout<< “The Sum of 5 + 2 is<< 5 + 2<<“n”<<“The Result pf 8 – 2 is“<<8 – 2 ;
The Output will be same but code is reduced.
The Sum of 5 + 2 is 7
The Result pf 8 – 2 is 6
Note: Stream insertion operator >> signifies that insert the value that follows
in to the stream named cout.
Object Oriented Programming using C++ - Preetha V AP/CSE 102
103. /* Write a C ++ Program that prints the sum of two
values */
#include <iostream.h> // for I/O Operation
#include<conio.h> // for clrscr() and getch() functions.
int main()
{
clrscr() ;
int value1, value2, sum ;
cout << “Enter First Value:”;
cin>>value1;
cout<<“Enter Second Value:”;
cin>>value2;
Object Oriented Programming using C++ - Preetha V AP/CSE 103
104. Program contd..
sum=value1+value2;
cout<<“The Sum of two given values is : “;
cout<<sum;
return 0;
}
Definition: Variable refers to a storage area whose contents can vary during
processing. In this example sum , value1 , valu2 are the variables.
NOTE: The Stream extraction operator >>, signifies “extract the next value” from the stream named cin and
assign it to the next named variable
Object Oriented Programming using C++ - Preetha V AP/CSE 104
105. OUTPUT OF PROGRAM
The output produced by the program is as follows,
Enter the First value: 6
Enter the Second value : 7
The Sum of the given value is : 13
Object Oriented Programming using C++ - Preetha V AP/CSE 105
106. CASCADING I/O OPERATOR
• The Multiple use of input or output operators (“>>” or “>>”) in one
statement is called cascading of I/O operators.
• For Example OUTPUT OPERATOR
cout<<“The sum of “;
cout<<value1;
cout<< “and “;
cout<<value2;
cout<<“ is “;
cout<<value1+value2;
This can be using cascading of output operator as,
cout<<“The sum of “<<value1<< “and “<<value2<<“ is “ <<value1+value2;
Object Oriented Programming using C++ - Preetha V AP/CSE 106
107. CASCADING I/O OPERATOR
• For Example INPUT OPERATOR
cout<<“Enter the two values “;
cin>>value1;
cin>>value2;
This can be using cascading of input operator as,
cout<<“Enter the two values “;
cin>>value1>>value2;
Object Oriented Programming using C++ - Preetha V AP/CSE 107
109. Arrays
• Array - a collection of a fixed number of
components wherein all of the components have
the same data type
• One-dimensional array - an array in which the
components are arranged in a list form
• The general form of declaring a one-dimensional
array is:
dataType arrayName[intExp];
where intExp is any expression that evaluates to a
positive integer
109
Object Oriented Programming using C++ - Preetha V AP/CSE
110. Declaring an array
• The statement
int num[5];
declares an array num of 5 components of the type int
• The components are num[0], num[1], num[2], num[3], and
num[4]
110
Object Oriented Programming using C++ - Preetha V AP/CSE
112. Accessing Array Components
• The general form (syntax) of accessing an array
component is:
arrayName[indexExp]
where indexExp, called index, is any expression whose value
is a nonnegative integer
• Index value specifies the position of the component in
the array
• The [] operator is called the array subscripting
operator
• The array index always starts at 0
112
Object Oriented Programming using C++ - Preetha V AP/CSE
117. Processing One-Dimensional Arrays
• Some basic operations performed on a one-
dimensional array are:
• Initialize
• Input data
• Output data stored in an array
• Find the largest and/or smallest element
• Each operation requires ability to step through the
elements of the array
• Easily accomplished by a loop
117
Object Oriented Programming using C++ - Preetha V AP/CSE
118. Accessing Array Components (continued)
• Consider the declaration
int list[100]; //list is an array
//of the size 100
int i;
• This for loop steps through each element of the array list
starting at the first element
for (i = 0; i < 100; i++) //Line 1
//process list[i] //Line 2
118
Object Oriented Programming using C++ - Preetha V AP/CSE
119. Accessing Array Components (continued)
• If processing list requires inputting data into list
• The statement in Line 2 takes the from of an input
statement, such as the cin statement
for (i = 0; i < 100; i++) //Line 1
cin >> list[i];
119
Object Oriented Programming using C++ - Preetha V AP/CSE
122. Array Index Out of Bounds
• If we have the statements:
double num[10];
int i;
• The component num[i] is a valid index if i = 0, 1,
2, 3, 4, 5, 6, 7, 8, or 9
• The index of an array is in bounds if the index >=0
and the index <= ARRAY_SIZE-1
122
Object Oriented Programming using C++ - Preetha V AP/CSE
123. Array Index Out of Bounds (continued)
• If either the index < 0 or the index >
ARRAY_SIZE-1
• then we say that the index is out of bounds
• There is no guard against indices that are out of
bounds
• C++ does not check if the index value is within range
123
Object Oriented Programming using C++ - Preetha V AP/CSE
124. Array Initialization
• As with simple variables
• Arrays can be initialized while they are being declared
• When initializing arrays while declaring them
• Not necessary to specify the size of the array
• Size of array is determined by the number of initial values in
the braces
• For example:
double sales[] = {12.25, 32.50, 16.90, 23,
45.68};
124
Object Oriented Programming using C++ - Preetha V AP/CSE
125. Partial Initialization
• The statement
int list[10] = {0};
declares list to be an array of 10 components and
initializes all components to zero
• The statement
int list[10] = {8, 5, 12};
declares list to be an array of 10 components, initializes
list[0] to 8, list[1] to 5, list[2] to 12 and all
other components are initialized to 0
125
Object Oriented Programming using C++ - Preetha V AP/CSE
126. Partial Initialization (continued)
• The statement
int list[] = {5, 6, 3};
declares list to be an array of 3 components and
initializes list[0] to 5, list[1] to 6, and list[2] to 3
• The statement
int list[25]= {4, 7};
declares list to be an array of 25 components
• The first two components are initialized to 4 and 7 respectively
• All other components are initialized to 0
126
Object Oriented Programming using C++ - Preetha V AP/CSE
127. Restrictions on Array Processing
Assignment does not work with arrays
In order to copy one array into another array we must
copy component-wise
127
Object Oriented Programming using C++ - Preetha V AP/CSE
128. Restrictions on Array Processing (continued)
128
Object Oriented Programming using C++ - Preetha V AP/CSE
129. Arrays as Parameters to Functions
• Arrays are passed by reference only
• The symbol & is not used when declaring an array
as a formal parameter
• The size of the array is usually omitted
129
Object Oriented Programming using C++ - Preetha V AP/CSE
130. Arrays as Parameters to Functions (continued)
• If the size of one-dimensional array is specified
when it is declared as a formal parameter
• It is ignored by the compiler
• The reserved word const in the declaration of
the formal parameter can prevent the function
from changing the actual parameter
130
Object Oriented Programming using C++ - Preetha V AP/CSE
135. Base Address of an Array
• The base address of an array is the address, or
memory location of the first array component
• If list is a one-dimensional array
• base address of list is the address of the component
list[0]
• When we pass an array as a parameter
• base address of the actual array is passed to the formal
parameter
• Functions cannot return a value of the type array
135
Object Oriented Programming using C++ - Preetha V AP/CSE
136. Parallel Arrays
• Two (or more) arrays are called parallel if their corresponding
components hold related information
• For example:
int studentId[50];
char courseGrade[50];
136
Object Oriented Programming using C++ - Preetha V AP/CSE
137. Two-Dimensional Arrays
• Two-dimensional Array: a collection of a fixed
number of components arranged in two dimensions
• All components are of the same type
• The syntax for declaring a two-dimensional array is:
dataType arrayName[intexp1][intexp2];
where intexp1 and intexp2 are expressions yielding
positive integer values
137
Object Oriented Programming using C++ - Preetha V AP/CSE
138. Two-Dimensional Arrays (continued)
• The two expressions intexp1 and intexp2
specify the number of rows and the number of
columns, respectively, in the array
• Two-dimensional arrays are sometimes called
matrices or tables
138
Object Oriented Programming using C++ - Preetha V AP/CSE
140. Accessing Array Components
• The syntax to access a component of a two-dimensional array is:
arrayName[indexexp1][indexexp2]
where indexexp1 and indexexp2 are expressions yielding
nonnegative integer values
• indexexp1 specifies the row position and indexexp2 specifies
the column position
140
Object Oriented Programming using C++ - Preetha V AP/CSE
142. Initialization
• Like one-dimensional arrays
• Two-dimensional arrays can be initialized when they
are declared
• To initialize a two-dimensional array when it is
declared
1. Elements of each row are enclosed within braces and
separated by commas
2. All rows are enclosed within braces
3. For number arrays, if all components of a row are not
specified, the unspecified components are initialized
to zero
142
Object Oriented Programming using C++ - Preetha V AP/CSE
143. Processing Two-Dimensional Arrays
• A two-dimensional array can be processed in
three different ways:
1. Process the entire array
2. Process a particular row of the array, called row
processing
3. Process a particular column of the array, called
column processing
143
Object Oriented Programming using C++ - Preetha V AP/CSE
144. Processing Two-Dimensional Arrays
(continued)
• Each row and each column of a two-dimensional
array is a one-dimensional array
• When processing a particular row or column of a
two-dimensional array
• we use algorithms similar to processing one-
dimensional arrays
144
Object Oriented Programming using C++ - Preetha V AP/CSE
150. Passing Two-Dimensional Arrays as
Parameters to Functions
• Two-dimensional arrays can be passed as parameters to a function
• By default, arrays are passed by reference
• The base address, which is the address of the first component of the
actual parameter, is passed to the formal parameter
150
Object Oriented Programming using C++ - Preetha V AP/CSE
151. Two-Dimensional Arrays
• Two-dimensional arrays are stored in row order
• The first row is stored first, followed by the second row,
followed by the third row and so on
• When declaring a two-dimensional array as a
formal parameter
• can omit size of first dimension, but not the second
• Number of columns must be specified
151
Object Oriented Programming using C++ - Preetha V AP/CSE
152. Multidimensional Arrays
• Multidimensional Array: collection of a fixed number
of elements (called components) arranged in n
dimensions (n >= 1)
• Also called an n-dimensional array
• General syntax of declaring an n-dimensional array is:
dataType arrayName[intExp1][intExp2]...[intExpn];
where intExp1, intExp2, … are constant
expressions yielding positive integer values
152
Object Oriented Programming using C++ - Preetha V AP/CSE
153. Multidimensional Arrays (continued)
• The syntax for accessing a component of an n-
dimensional array is:
arrayName[indexExp1][indexExp2]...[indexExpn]
where indexExp1,indexExp2,..., and indexExpn
are expressions yielding nonnegative integer values
• indexExpi gives the position of the array
component in the ith dimension
153
Object Oriented Programming using C++ - Preetha V AP/CSE
154. Multidimensional Arrays (continued)
• When declaring a multi-dimensional array as a formal
parameter in a function
• can omit size of first dimension but not other dimensions
• As parameters, multi-dimensional arrays are passed
by reference only
• A function cannot return a value of the type array
• There is no check if the array indices are within
bounds
154
Object Oriented Programming using C++ - Preetha V AP/CSE
155. Summary
• An array is a structured data type with a fixed
number of components
• Every component is of the same type
• Components are accessed using their relative positions in
the array
• Elements of a one-dimensional array are arranged in
the form of a list
• An array index can be any expression that evaluates
to a non-negative integer
• The value of the index must always be less than the
size of the array
155
Object Oriented Programming using C++ - Preetha V AP/CSE
156. Summary (continued)
• The base address of an array is the address of the
first array component
• In a function call statement, when passing an array
as an actual parameter, you use only its name
• As parameters to functions, arrays are passed by
reference only
• A function cannot return a value of the type array
• In C++, C-strings are null terminated and are stored
in character arrays
156
Object Oriented Programming using C++ - Preetha V AP/CSE
157. Summary (continued)
• Commonly used C-string manipulation functions
include: strcpy, strcmp, and strlen
• Parallel arrays are used to hold related information
• In a two-dimensional array, the elements are
arranged in a table form
157
Object Oriented Programming using C++ - Preetha V AP/CSE
158. Summary (continued)
• To access an element of a two-dimensional array,
you need a pair of indices: one for the row position
and one for the column position
• In row processing, a two-dimensional array is
processed one row at a time
• In column processing, a two-dimensional array is
processed one column at a time
158
Object Oriented Programming using C++ - Preetha V AP/CSE
159. C++ Strings
C++ provides following two types of string representations −
• The C-style character string.
• The string class type introduced with Standard C++.
160. The C-Style Character String
• The C-style character string originated within the C language and
continues to be supported within C++. This string is actually a one-
dimensional array of characters which is terminated by
a null character '0'. Thus a null-terminated string contains the
characters that comprise the string followed by a null.
161. • The following declaration and initialization create a string consisting
of the word "Hello". To hold the null character at the end of the array,
the size of the character array containing the string is one more than
the number of characters in the word "Hello.“
If you follow the rule of array initialization, then you can write the
above statement as follows −
Char greetings[] = “Hello”;
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
162. Following is the memory presentation of above defined string in C/C++ −
Actually, you do not place the null character at the end of a string constant.
The C++ compiler automatically places the '0' at the end of the string when it initializes the array.
Let us try to print above-mentioned string −
163. #include <iostream>
using namespace std;
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0’};
cout << "Greeting message: ";
cout << greeting << endl; return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
164. Sr.No Function & Purpose
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater
than 0 if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
C++ supports a wide range of functions that manipulate null-terminated strings −
165. #include <iostream>
#include <cstring>
using namespace std;
int main ()
{
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ; // copy str1 into str3
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl; // concatenates str1 and str2
strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl; // total lenghth of str1 after concatenation
len = strlen(str1);
cout << "strlen(str1) : " << len << endl; return 0;
}
167. The String Class in C++
• The standard C++ library provides a string class type that supports all
the operations mentioned above, additionally much more
functionality. Let us check the following example −
168. #include <iostream>
#include <string>
using namespace std;
int main ()
{ string str1 = "Hello";
string str2 = "World";
string str3; int len ; // copy str1 into str3 str3 = str1;
cout << "str3 : " << str3 << endl; // concatenates str1 and str2
str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl; // total length of str3 after concatenation
len = str3.size();
cout << "str3.size() : " << len << endl; return 0;
}
170. String Comparison
• C-strings are compared character by character
using the collating sequence of the system
• If we are using the ASCII character set
1. The string "Air" is smaller than the string "Boat"
2. The string "Air" is smaller than the string "An"
3. The string "Bill" is smaller than the string
"Billy"
4. The string "Hello" is smaller than "hello"
170
Object Oriented Programming using C++ - Preetha V AP/CSE
171. Strings are used for storing text.
A string variable contains a collection of characters surrounded by double quotes:
172. Reading and Writing Strings
• String Input
• Aggregate operations are allowed for string input
• cin >> name; stores the next input string in name
• Strings that contain blanks cannot be read using the
extraction operator >>
172
Object Oriented Programming using C++ - Preetha V AP/CSE
173. Reading and Writing Strings (continued)
• String Output
• The statement cout << name; outputs the content of name on the screen
• The insertion operator << continues to write the contents of name until it
finds the null character
• If name does not contain the null character, then we will see strange output:
<< continues to output data from memory adjacent to name until '0' is
found
173
Object Oriented Programming using C++ - Preetha V AP/CSE
174. Approximate Terminology
• instance = object
• field = instance variable
• method = function
• sending a message to an object =calling a function
Object Oriented Programming using C++ - Preetha V AP/CSE 174
176. • The pointer in C++ language is a variable, it is also known as locator or
indicator that points to an address of a value.
• The symbol of an address is represented by a pointer. In addition to creating and
modifying dynamic data structures, they allow programs to emulate call-by-
reference. One of the principal applications of pointers is iterating through the
components of arrays or other data structures. The pointer variable that refers to
the same data type as the variable you're dealing with has the address of that
variable set to it (such as an int or string).
Syntax
datatype *var_name;
int *ptr; // ptr can point to an address which holds int data
Object Oriented Programming using C++ - Preetha V AP/CSE
177. How to use a pointer?
• Establish a pointer variable.
• employing the unary operator (&), which yields the address of the variable, to
assign a pointer to a variable's address.
• Using the unary operator (*), which gives the variable's value at the address
provided by its argument, one can access the value stored in an address.
Object Oriented Programming using C++ - Preetha V AP/CSE
179. Advantage of pointer
1)Pointer reduces the code and improves the performance, it is used to
retrieving strings, trees etc. and used with arrays, structures and functions.
2) We can return multiple values from function using pointer.
3) It makes you able to access any memory location in the computer's
memory.
Object Oriented Programming using C++ - Preetha V AP/CSE
180. Symbols used in pointer
Symbol Name Description
& (ampersand sign) Address operator Determine the address
of a variable.
∗ (asterisk sign) Indirection operator Access the value of an
address.
Object Oriented Programming using C++ - Preetha V AP/CSE
181. Declaring a pointer
• int ∗ a; //pointer to int
• char ∗ c; //pointer to char
Object Oriented Programming using C++ - Preetha V AP/CSE
182. Pointer Example
Let's see the simple example of using pointers
printing the address and value.
#include <iostream>
using namespace std;
int main()
{
int number=30;
int ∗ p;
p=&number;//stores the address of number variable
cout<<"Address of number variable is:"<<&number<<endl;
cout<<"Address of p variable is:"<<p<<endl;
cout<<"Value of p variable is:"<<*p<<endl;
return 0;
} Object Oriented Programming using C++ - Preetha V AP/CSE
183. Output:
Address of number variable is:0x7ffccc8724c4
Address of p variable is:0x7ffccc8724c4
Value of p variable is:30
Object Oriented Programming using C++ - Preetha V AP/CSE
184. Pointer Program to swap 2 numbers without using
3rd variable
#include <iostream>
using namespace std;
int main()
{
int a=20,b=10,∗p1=&a,∗p2=&b;
cout<<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
∗p1=∗p1+∗p2;
∗p2=∗p1-∗p2;
∗p1=∗p1-∗p2;
cout<<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<<endl;
return 0;
} Object Oriented Programming using C++ - Preetha V AP/CSE
185. Output:
Before swap: ∗p1=20 ∗p2=10
After swap: ∗p1=10 ∗p2=20
Object Oriented Programming using C++ - Preetha V AP/CSE
186. What are Pointer and string literals?
• String literals are arrays of character sequences with null ends. The
elements of a string literal are arrays of type const char (because
characters in a string cannot be modified) plus a terminating null-
character.
Object Oriented Programming using C++ - Preetha V AP/CSE
187. What is a void pointer?
• This unique type of pointer, which is available in C++, stands in for the
lack of a kind. Pointers that point to a value that has no type are
known as void pointers (and thus also an undetermined length and
undetermined dereferencing properties). This indicates that void
pointers are very flexible because they can point to any data type.
This flexibility has benefits. Direct dereference is not possible with
these pointers. Before they may be dereferenced, they must be
converted into another pointer type that points to a specific data
type.
Object Oriented Programming using C++ - Preetha V AP/CSE
188. What is a invalid pointer?
• A pointer must point to a valid address, not necessarily to useful
items (like for arrays). We refer to these as incorrect pointers.
Additionally, incorrect pointers are uninitialized pointers.
• int *ptr1;
• int arr[10];
• int *ptr2 = arr+20;
• Here, ptr1 is not initialized, making it invalid, and ptr2 is outside of
the bounds of arr, making it likewise weak. (Take note that not all
build failures are caused by faulty references.)
Object Oriented Programming using C++ - Preetha V AP/CSE
189. What is a null pointer?
• A null pointer is not merely an incorrect address; it also points
nowhere. Here are two ways to mark a pointer as NULL:
Object Oriented Programming using C++ - Preetha V AP/CSE
190. What is a pointer to a pointer?
In C++, we have the ability to build a pointer to another pointer, which might
then point to data or another pointer. The unary operator (*) is all that is
needed in the syntax for declaring the pointer for each level of indirection.
char a;
char *b;
char ** c;
a = 'g';
b = &a;
c = &b;
Here b points to a char that stores 'g', and c points to the pointer b.
Object Oriented Programming using C++ - Preetha V AP/CSE
191. What are references and pointers?
Call-By-Value
Call-By-Reference with a Pointer Argument
Call-By-Reference with a Reference Argument
Object Oriented Programming using C++ - Preetha V AP/CSE
192. Example
#include
using namespace std;
// Pass-by-Value
int square1(int n)
{cout << "address of n1 in square1(): " << &n << "n";
n *= n;
return n;
}
// Pass-by-Reference with Pointer Arguments
void square2(int* n)
{
cout << "address of n2 in square2(): " << n << "n";
*n *= *n;
}
Object Oriented Programming using C++ - Preetha V AP/CSE
193. // Pass-by-Reference with Reference Arguments
void square3(int& n)
{
cout << "address of n3 in square3(): " << &n << "n";
n *= n;
}
Object Oriented Programming using C++ - Preetha V AP/CSE
194. void example()
{
// Call-by-Value
int n1 = 8;
cout << "address of n1 in main(): " << &n1 << "n";
cout << "Square of n1: " << square1(n1) << "n";
cout << "No change in n1: " << n1 << "n";
// Call-by-Reference with Pointer Arguments
int n2 = 8;
cout << "address of n2 in main(): " << &n2 << "n";
square2(&n2);
cout << "Square of n2: " << n2 << "n";
cout << "Change reflected in n2: " << n2 << "n";
Object Oriented Programming using C++ - Preetha V AP/CSE
195. // Call-by-Reference with Reference Arguments
int n3 = 8;
cout << "address of n3 in main(): " << &n3 << "n";
square3(n3);
cout << "Square of n3: " << n3 << "n";
cout << "Change reflected in n3: " << n3 << "n";
}
// Driver program
int main() { example(); }
Object Oriented Programming using C++ - Preetha V AP/CSE
197. UNIT 2 - Classes and Objects
Classes and Objects - Class specification: Class Members, Access
Specifier, Scope resolution operator- Class Instantiation - Accessing
class members- Passing and returning objects - Array of objects –
Constructors: Parameterized constructors - Default arguments – Copy
Constructor - Constructor overloading, Destructors - new, delete
operators - “this” pointer - Friend classes and friend functions.
Object Oriented Programming using C++ - Preetha V AP/CSE 197
198. What is Class?
• The mechanism that allows you to combine data and the
function in a single unit is called a class.
• Once a class is defined, you can declare variables of that type.
• A class variable is called object or instance. In other words, a
class would be the data type, and an object would be the
variable.
• Classes are generally declared using the keyword class.
Object Oriented Programming using C++ - Preetha V AP/CSE 198
199. What is Class?
• A class is the collection of related data and function under a
single name.
• A C++ program can have any number of classes.
• When related data and functions are kept under a class, it helps
to visualize the complex problem efficiently and effectively.
• A class is a definition of an object. It's a type just like int .
• A class resembles a struct with just one difference : all struct
members are public by default.
• All classes members are private.
Object Oriented Programming using C++ - Preetha V AP/CSE 199
200. What is Class?
• A class is a user defined type or data structure declared with
keyword class that has data and functions (also called
methods) as its members whose access is governed by the
three access specifiers private, protected or public (by default
access to members of a class is private).
• A class (declared with keyword class) in C++ differs from a
structure (declared with keyword struct) as by default,
members are private in a class while they are public in a
structure.
Object Oriented Programming using C++ - Preetha V AP/CSE 200
201. Defining Class
class class_name
{
Data Members;
Methods;
};
OR
class class_name
{
private: members1;
protected: members2;
public: members3;
};
Object Oriented Programming using C++ - Preetha V AP/CSE 201
202. Defining Class
• private members of a class are accessible only from within
other members of the same class. You cannot access it
outside of the class.
• protected members are accessible from members of their
same class and also from members of their derived classes.
protected members are accessible from other members of the
same class (or from their "friends"), but also from members of
their derived classes.
Object Oriented Programming using C++ - Preetha V AP/CSE 202
203. Defining Class
• public members are accessible from anywhere where the
object is visible.
By default, all members of a class declared with the class
keyword have private access for all its members. Therefore, any
member that is declared before one other class specifies
automatically has private access.
Object Oriented Programming using C++ - Preetha V AP/CSE 203
204. Defining Member Function of Class
Member functions can be defined in two ways,
1. Inside the class
2. Outside the class
Object Oriented Programming using C++ - Preetha V AP/CSE 204
205. Object Declaration
• Once a class is defined, you can declare objects of that type.
The syntax for declaring a object is the same as that for
declaring any other variable.
• The following statements declare two objects of type circle:
Circle c1, c2;
Circle is class and c1 and c2 are the objects.
• Once the class is defined you can define any number of
objects.
Object Oriented Programming using C++ - Preetha V AP/CSE 205
206. Object Declaration
Accessing Class Members
Once an object of a class is declared, it can
access the public members of the class using ( . )
dot membership operator.
c1.setRadius(2.5);
Object Oriented Programming using C++ - Preetha V AP/CSE 206
207. Access modifiers
• Access modifiers (or access specifiers)
are keywords in object-oriented languages that set the
accessibility of classes, methods, and other members.
• Access modifiers are a specific part of programming language
syntax used to facilitate the encapsulation of components
Object Oriented Programming using C++ - Preetha V AP/CSE 207
208. Access modifiers
• C++ uses the three modifiers called public, protected,
and private.
• Java has public, package, protected, and private.
Object Oriented Programming using C++ - Preetha V AP/CSE 208
209. Local Classes in C++
A class declared inside a function becomes local to that function and is
called Local Class in C++.
For example, in the following program, Test is a local class in fun().
void fun()
{
class Test // local to fun
{
Int mark1;
Int mark3;
/* members of Test class */
}; Object Oriented Programming using C++ - Preetha V AP/CSE 209
210. Global Classes in C++
A class declared outside the body of all the function in a program is called Global Class in C++.
For example
class Sample // class name
{
int x; //member variables or data members
public:
void readx() // function name or member function declaration
{
cin>>x;
}
};
void main()
{
Sample s1;
s1.readx();
}
Object Oriented Programming using C++ - Preetha V AP/CSE 210
211. Local and Global Objects in C++
class Sample
{
int x;
public: void readx()
{
cin>>x;
}
};
Sample s1; // Global Object
void main()
{
Sample s2; // Local Object
s1.readx();
}
Object Oriented Programming using C++ - Preetha V AP/CSE 211
212. “this” Pointer
• “this” Pointer
• Every object in C++ has access to its own address through an
important pointer called this pointer. The this pointer is an implicit
parameter to all member functions. Therefore, inside a member
function, this may be used to refer to the invoking object.
• Friend functions do not have a this pointer, because friends are not
members of a class. Only member functions have a this pointer.
Object Oriented Programming using C++ - Preetha V AP/CSE 212
213. Let us try the following example to understand the
concept of this pointer:
#include <iostream>
using namespace std;
class Box
{
public:
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
Object Oriented Programming using C++ - Preetha V AP/CSE 213
214. height = h;
}
double Volume()
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length;
double breadth;
double height;
// Length of a box
// Breadth of a box
// Height of a box
};
Object Oriented Programming using C++ - Preetha V AP/CSE 214
215. int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1" <<endl;
}
else
{
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1 Object Oriented Programming using C++ - Preetha V AP/CSE 215
216. CONSTRUCTOR
• A class constructor is a special member function of a class that is
executed whenever we create new objects of that class
• A constructor will have exact same name as the class and it does not
have any return type at all, not even void. Constructors can be very
useful for setting initial values for certain member variables.
• Types of Constructor
Default Constructor
Overloaded Constructor
Parameterized Constructor
Copy Constructor
Object Oriented Programming using C++ - Preetha V AP/CSE 216
217. Scope resolution operator
• Member functions can be defined within the class definition or
separately using scope resolution operator ::
• Defining a member function within the class definition declares the
function inline, even if you do not use the inline specifier.
• So either you can defineVolume() function as below:
Object Oriented Programming using C++ - Preetha V AP/CSE 217
218. class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void)
{
return length * breadth * height;
}
};
If you like, you can define the same function outside the class using the scope resolution operator (::)
as follows:
Syntax: datatype class name::function name()
Object Oriented Programming using C++ - Preetha V AP/CSE 218
219. Example:
double Box::getVolume(void)
{
return length * breadth * height;
}
• Here, only important point is that you would have to use class name just before
operator.
• A member function will be called using a dot operator (.) on a object where it will
manipulate data related to that object only as follows:
Box myBox; // Create an object
myBox.getVolume(); // Call member function for the object
Object Oriented Programming using C++ - Preetha V AP/CSE 219
220. Let us put above concepts to set and get the value of different class members in a class:
#include <iostream>
using namespace std;
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
//Member functions declaration
double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};
Object Oriented Programming using C++ - Preetha V AP/CSE 220
222. // Main function for the program
int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
Object Oriented Programming using C++ - Preetha V AP/CSE 222
223. // volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume<<endl; return 0;
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Object Oriented Programming using C++ - Preetha V AP/CSE 223
224. Need for constructor
• Constructor is special member functions.
• It is a function used to initialize the object itself.
• The data within the class cannot be initialized at that time of declaration
in class.
• Constructor has the same name as the name of the class.
• This is because the declaration of a class serves only as a template, and
no memory is allocated at the time of declaration.
• This problem can be solved by writing an initializing function – a
constructor.
• Constructor is a basically a function used to initialize variables, to allocate
memory and soon.
• This function will be automatically called as soon as an object is created.
There is no need to call the function to initialize the variables.
Object Oriented Programming using C++ - Preetha V AP/CSE 224
226. How constructors are different from a normal
member function?
• A constructor is different from normal functions in following ways:
• Constructor has same name as the class itself
• Constructors don’t have return type
• A constructor is automatically called when an object is created.
• If we do not specify a constructor, C++ compiler generates a default
constructor for us (expects no parameters and has an empty body).
Object Oriented Programming using C++ - Preetha V AP/CSE 226
227. Default Constructors: Default constructor is the constructor which doesn’t take
any argument. It has no parameters.
#include <iostream>
using namespace std;
class construct
{
public:
int a, b;
construct() // Default Constructor
{
a = 10;
b = 20;
}
};
int main()
{
// Default constructor called automatically
// when the object is created
construct c;
cout << "a: "<< c.a << endl << "b: "<< c.b;
return 1;
}
Output:
a: 10
b: 20
Object Oriented Programming using C++ - Preetha V AP/CSE 227
228. Parameterized Constructors: It is possible to pass arguments to constructors. Typically, these
arguments help initialize an object when it is created. To create a parameterized constructor, simply
add parameters to it the way you would to any other function. When you define the constructor’s
body, use the parameters to initialize the object.
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}
Output:
p1.x = 10, p1.y = 15
Object Oriented Programming using C++ - Preetha V AP/CSE 228
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) // Parameterized Constructor
{ x = x1; x=10
y = y1; y=15
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
229. Copy Constructor: A copy constructor is a member function which initializes an object using another object
of the same class. A copy constructor has the following general function prototype:
ClassName (const ClassName &old_obj);
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}
Point(const Point &p2)
{x = p2.x;
y = p2.y;
} // Copy constructor
int getX() { return x; }
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
Output:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15
Object Oriented Programming using C++ - Preetha V AP/CSE 229
230. #include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1;
y = y1;
}
Point(const Point &p2)
{
x = p2.x;
y = p2.y;
} // Copy constructor
int getX()
{
return x;
}
int getY()
{
return y;
}
}; Object Oriented Programming using C++ - Preetha V AP/CSE 230
231. Copy Constructor
#include<iostream>
using namespace std;
class Sample
{
private:
int x, y; //data members
public:
Sample(int x1, int y1)
{
x = x1;
y = y1;
}
/* Copy constructor */
Sample (const Sample &sam)
{
x = sam.x;
y = sam.y;
}
void display()
{
cout<<x<<" "<<y<<endl;
}
};
int main()
{
Sample obj1(10, 15); // Normal const
Sample obj2 = obj1; // Copy constructor
cout<<"Normal constructor : ";
obj1.display();
cout<<"Copy constructor : ";
obj2.display();
return 0;
}
Output: Normal constructor : 10 15
Copy constructor : 10 15
Object Oriented Programming using C++ - Preetha V AP/CSE 231
232. Constructor Overloading in C++
• In C++, We can have more than one constructor in a class with same name,
as long as each has a different list of arguments.
• This concept is known as Constructor Overloading and is quite similar
to function overloading.
• Overloaded constructors essentially have the same name (name of the class)
and different number of arguments.
• A constructor is called depending upon the number and type of arguments
passed.
• While creating the object, arguments must be passed to let compiler know,
which constructor needs to be called.
Object Oriented Programming using C++ - Preetha V AP/CSE 232
233. Parameterized Constructor:
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len);
// This is the constructor
private: double length;
};
// Member functions definitions including constructor
Line::Line( double len)
{
cout << "Object is being created, length = " << len
<< endl;
length = len;
}
void Line::setLength( double len )
{ length = len;}
double Line::getLength( void )
{ return length;}
// Main function for the program
int main( )
{ Line line(10.0);
// get initially set length.
cout << "Length of line : " <<
line.getLength() <<endl;
// set line length again line.setLength(6.0);
cout << "Length of line : " <<
line.getLength() <<endl;
return 0;
}
OUTPUT:
Object is being created, length = 10
Length of line : 10
Length of line : 6
233
Object Oriented Programming using C++ - Preetha V AP/CSE
234. Destructors in C++
• What is destructor?
Destructor is a member function which destructs or deletes an object.
• When is destructor called?
A destructor is automatically called when:
1) The program finished execution.
2) When a scope (the { } parenthesis) containing local variable ends.
3) When you call the delete operator.
• How destructors are different from a normal member function?
Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything.
Object Oriented Programming using C++ - Preetha V AP/CSE 234
235. Destructors:
• Destructor is a member function which destructs or deletes an object.
• Destructor called?
A destructor function is called automatically when the object goes out
of scope:
(1) the function ends
(2) the program ends
(3) a block containing local variables ends
(4) a delete operator is called
Object Oriented Programming using C++ - Preetha V AP/CSE 235
236. Destructors - new, delete operators
How destructors are different from a normal member function?
Destructors have same name as the class preceded by a tilde (~)
Destructors don’t take any argument and don’t return anything
Object Oriented Programming using C++ - Preetha V AP/CSE 236
237. class String
{
private:
char *s;
int size;
public:
String(char *); // constructor
~String(); // destructor
};
String::String(char *c)
{
size = strlen(c);
s = new char[size+1];
strcpy(s,c);
}
String::~String()
{
delete []s;
}
Object Oriented Programming using C++ - Preetha V AP/CSE 237
238. STATIC MEMBER
• In normal situations when we instantiate objects of a class each object gets its own copy of all
normal member variables.
• When we declare a member of a class as static it means no matter how many objects of the class
are created, there is only one copy of the static member.
• This means one single copy of that data member is shared between all objects of that class.
• All static data is initialized to zero when the first object is created, if no other initialization is
present.
• Static data members can be initialized outside the class using the scope resolution operator (::) to
identify which class it belongs to.
• Since Static data members are class level variables, we do not require the object to access these
variables and they can be accessed simply by using the class name and scope resolution(::)
operator with the variable name to access its value.
• Also a static data member cannot be private.
• A very common use of static data members is to keep a count of total objects of a particular class
(program counter kind of application)
Object Oriented Programming using C++ - Preetha V AP/CSE 238
240. STATIC MEMBER
• Static Data member has the following properties:
• It is initialized by zero when first object of class is created.
• Only one copy of static data member is created for the entire class and all object share the same copy.
• Its scope is within class but its lifetime is entire program.
• They are used to store the value that are common for all the objects.
• Static variable can be declared using the following syntax:
static data-type variable-name;
• The above syntax only declare the static variable. We can initialize static variable by using following
syntax:
data-type class-name :: variable-name = initial-value ;
• Along with the definition we can also initialize the static variable.
• If static data members (variables) are declared under the public section than it can be accessed from outside
the class and if it is declared in private section than it can only be accessed within the class itself.
• Static variables are also known as class variables because they are not the variables of any particular class.
Object Oriented Programming using C++ - Preetha V AP/CSE 240
241. Static Member Function
• By declaring a function member as static, you make it independent of any
particular object of the class. A static member function can be called even if no
objects of the class exist and the static functions are accessed using only the class
name and the scope resolution operator ::
• A static member function can only access static data member, other static member
functions and any other functions from outside the class.
• Static member functions have a class scope and they do not have access to the this
pointer of the class. You could use a static member function to determine whether
some objects of the class have been created or not.
Object Oriented Programming using C++ - Preetha V AP/CSE 241
242. Static Member Function
• Static member function has following properties:
• A static function can be access only by other static data member (variables) and
function declared in the class.
• A static function is called using class name instead of object name.
Object Oriented Programming using C++ - Preetha V AP/CSE 242
243. private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects.
cout << "Total objects: " << Box::objectCount <<
endl;
return 0;
}
OUTPUT:
Constructor called.
Constructor called.
Total objects: 2
243
#include <iostream>
using namespace std;
class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{ return length * breadth * height; }
Object Oriented Programming using C++ - Preetha V AP/CSE
244. static int getCount()
{ return objectCount; }
private: double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class
Boxint Box::objectCount = 0;
int main(void)
{
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects after creating object.
cout << "Final Stage Count: " << Box::getCount() << endl;
return 0;
}
OUTPUT:
Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2
244
#include <iostream>
using namespace std;
class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{ cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{ return length * breadth * height; }
Object Oriented Programming using C++ - Preetha V AP/CSE
245. • STORAGE CLASSES:
• A storage class defines the scope (visibility) and life-time of variables
and/or functions within a C++ Program. These specifiers precede the type
that they modify. There are following storage classes, which can be used in
a C++ Program
• auto
• register
• static
• extern
245
Object Oriented Programming using C++ - Preetha V AP/CSE
246. Array of Objects
• An object of class represents a single record in memory, if we want
more than one record of class type, we have to create an array of
class or object.
• As we know, an array is a collection of similar type, therefore an array
can be a collection of class type.
Object Oriented Programming using C++ - Preetha V AP/CSE 246
247. Syntax of Array of Objects
class class-name
{
datatype var1;
datatype var2;
- - - - - - - - - -
datatype varN;
method1();
method2();
- - - - - - - - - -
methodN();
};
class-name obj[ size ];
Object Oriented Programming using C++ - Preetha V AP/CSE 247
248. void PutData() //Statement 2 : Defining PutData()
{
cout<<"n"<<Id<<"t"<<Name<<"t"<<Age<<"t"<<Salary;
}
};
void main()
{ int i;
Employee E[3]; //Statement 3 : Creating Array of 3
Employees
for(i=0;i<3;i++)
{
cout<<"nEnter details of "<<i+1<<" Employee";
E[i].GetData();
} cout<<"nDetails of Employees";
for(i=0;i<3;i++)
E[i].PutData();
}
Object Oriented Programming using C++ - Preetha V AP/CSE 248
#include<iostream.h>
#include<conio.h>
class Employee
{ int Id;
char Name[25];
int Age;
long Salary;
public:
void GetData() //Statement 1 : Defining GetData()
{
cout<<"ntEnter Employee Id : ";
cin>>Id;
cout<<"ntEnter Employee Name : ";
cin>>Name;
cout<<"ntEnter Employee Age : ";
cin>>Age;
cout<<"ntEnter Employee Salary : ";
cin>>Salary;
}
249. Friend function
• A friend function of a class is defined outside that class scope but it has the
right to access all private and protected members of the class.
• A friend can be a function, function template, or member function, or a
class or class template, in which case the entire class and all of its members
are friends.
• Declaration of friend function in C++
class class_name
{
... .. ...
friend return_type function_name(argument/s);
... .. ...
}
Object Oriented Programming using C++ - Preetha V AP/CSE 249