SlideShare uma empresa Scribd logo
1 de 22
C++ Classes
              &
Object Oriented Programming
Object Oriented Programming
 Programmer thinks about and defines the
  attributes and behavior of objects.

 Often the objects are modeled after real-
  world entities.

 Very different approach than function-based
  programming (like C).
Object Oriented Programming
 Object-oriented programming (OOP)
  – Encapsulates data (attributes) and functions
    (behavior) into packages called classes.
 So, Classes are user-defined (programmer-
  defined) types.
  – Data (data members)
  – Functions (member functions or methods)
 In other words, they are structures +
  functions
Classes in C++
 A class definition begins with the keyword
  class.
 The body of the class is contained within a
  set of braces, { } ; (notice the semi-colon).
                  class class_name       Any valid
                  }                      identifier
                  .…
                  .…
                                     Class body (data member
                  .…
                                     + methods)
                                       methods
                  ;{
++Classes in C
 Within the body, the keywords private: and
  public: specify the access level of the
  members of the class.
  – the default is private.

 Usually, the data members of a class are
  declared in the private: section of the class
  and the member functions are in public:
  section.
Classes in C++

class class_name
}
:private           private members or
          …        methods
          …
          …
    public:
          …        Public members or methods
          …
          …
;{
Classes in C++
 Member access specifiers
  – public:
      can be accessed outside the class directly.
        – The public stuff is the interface.
  – private:
      Accessible only to member functions of class
      Private members and methods are for internal use
       only.
Class Example
 This class example shows how we can
  encapsulate (gather) a circle information
  into one package (unit or class)
                                           No need for others classes to
    class Circle                           access and retrieve its value
                                           directly. The
    {
                                           class methods are responsible for
       private:                            that only.
             double radius;
       public:
             void setRadius(double r);    They are accessible from outside
    double getDiameter();                 the class, and they can access the
             double getArea();            member (radius)
             double getCircumference();
    };
Creating an object of a Class
 Declaring a variable of a class type creates an
  object. You can have many variables of the same
  type (class).
   – Instantiation
 Once an object of a certain class is instantiated, a
  new memory location is created for it to store its
  data members and code
 You can instantiate many objects from a class
  type.
   – Ex) Circle c; Circle *c;
Special Member Functions
 Constructor:
  – Public function member
  – called when a new object is created
    (instantiated).
  – Initialize data members.
  – Same name as class
  – No return type
  – Several constructors
     Function overloading
Special Member Functions

class Circle
                                      Constructor with no
{
                                      argument
   private:
         double radius;
   public:                            Constructor with one
         Circle();                    argument
         Circle(int r);
          void setRadius(double r);
         double getDiameter();
         double getArea();
         double getCircumference();
};
Implementing class methods
    Class implementation: writing the code of class
     methods.
    There are two ways:
    1. Member functions defined outside class
           Using Binary scope resolution operator (::)
           “Ties” member name to class name
           Uniquely identify functions of particular class
           Different classes can have member functions with same
            name
    –   Format for defining member functions
        ReturnType ClassName::MemberFunctionName( ){
           …
        }
Implementing class methods
2. Member functions defined inside class
  – Do not need scope resolution operator, class
    name;
       class Circle
       {                                                   Defined
          private:                                         inside
                double radius;                             class
          public:
                Circle() { radius = 0.0;}
                Circle(int r);
                void setRadius(double r){radius = r;}
                double getDiameter(){ return radius *2;}
                double getArea();
                double getCircumference();
       };
class Circle
{
   private:
          double radius;
   public:
          Circle() { radius = 0.0;}
          Circle(int r);
          void setRadius(double r){radius = r;}
          double getDiameter(){ return radius *2;}
          double getArea();
          double getCircumference();
};
Circle::Circle(int r)
{
                                                     Defined outside class
   radius = r;
}
double Circle::getArea()
{
   return radius * radius * (22.0/7);
}
double Circle:: getCircumference()
{
   return 2 * radius * (22.0/7);
}
Accessing Class Members
 Operators to access class members
  – Identical to those for structs
  – Dot member selection operator (.)
     Object
     Reference to object
  – Arrow member selection operator (->)
     Pointers
class Circle
{
   private:
          double radius;
   public:                                                   The first
          Circle() { radius = 0.0;}                          The second
                                                           constructor is
          Circle(int r);                                    constructor is
                                                              called
          void setRadius(double r){radius = r;}                 called
          double getDiameter(){ return radius *2;}
          double getArea();
                                      void main()                 Since radius is a
          double getCircumference();
                                      {                           private class data
};                                          Circle c1,c2(7);           member
Circle::Circle(int r)
{                                           cout<<“The area of c1:”
   radius = r;                                  <<c1.getArea()<<“n”;
}
double Circle::getArea()                    //c1.raduis = 5;//syntax error
{                                           c1.setRadius(5);
   return radius * radius * (22.0/7);
                                            cout<<“The circumference of c1:”
}                                               << c1.getCircumference()<<“n”;
double Circle:: getCircumference()
{                                           cout<<“The Diameter of c2:”
   return 2 * radius * (22.0/7);                <<c2.getDiameter()<<“n”;
}                                     }
class Circle
{
   private:
          double radius;
   public:
          Circle() { radius = 0.0;}
          Circle(int r);
          void setRadius(double r){radius = r;}
          double getDiameter(){ return radius *2;}
          double getArea();
          double getCircumference();
};
Circle::Circle(int r)                 void main()
                                      {
{
                                            Circle c(7);
   radius = r;                              Circle *cp1 = &c;
}                                           Circle *cp2 = new Circle(7);
double Circle::getArea()
{                                           cout<<“The are of cp2:”
   return radius * radius * (22.0/7);                  <<cp2->getArea();
}
double Circle:: getCircumference() }
{
   return 2 * radius * (22.0/7);
}
Destructors
 Destructors
  – Special member function
  – Same name as class
        Preceded with tilde (~)
  –   No arguments
  –   No return value
  –   Cannot be overloaded
  –   Before system reclaims object’s memory
        Reuse memory for new objects
        Mainly used to de-allocate dynamic memory locations
Another class Example
 This class shows how to handle time parts.
               class Time
               {
                   private:
                       int *hour,*minute,*second;
                   public:
                       Time();
                       Time(int h,int m,int s);
                       void printTime();
                       void setTime(int h,int m,int s);
                       int getHour(){return *hour;}
                       int getMinute(){return *minute;}
  Destructor           int getSecond(){return *second;}
                       void setHour(int h){*hour = h;}
                       void setMinute(int m){*minute = m;}
                       void setSecond(int s){*second = s;}
                       ~Time();
               };
Time::Time()
                      {
                             hour = new int;
                             minute = new int;
                             second = new int;
                             *hour = *minute = *second = 0;
                      }

Dynamic locations     Time::Time(int h,int m,int s)
should be allocated   {
  to pointers first
                             hour = new int;
                             minute = new int;
                             second = new int;
                             *hour = h;
                             *minute = m;
                             *second = s;
                      }

                      void Time::setTime(int h,int m,int s)
                      {
                             *hour = h;
                             *minute = m;
                             *second = s;
                      }
void Time::printTime()
{
     cout<<"The time is : ("<<*hour<<":"<<*minute<<":"<<*second<<")"
               <<endl;
}
                                   Destructor: used here to de-
Time::~Time()                       allocate memory locations
{
       delete hour; delete minute;delete second;
}

void main()
                                Output:
{
        Time *t;                The time is : (3:55:54)
        t= new Time(3,55,54);   The time is : (7:17:43)
        t->printTime();         Press any key to continue

       t->setHour(7);
       t->setMinute(17);
       t->setSecond(43);

       t->printTime();              When executed, the
                                    destructor is called
       delete t;
}
Reasons for OOP
1. Simplify programming
2. Interfaces
    Information hiding:
      – Implementation details hidden within classes themselves

3. Software reuse
     Class objects included as members of other
      classes

Mais conteúdo relacionado

Mais procurados

Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1Vineeta Garg
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3Shaili Choudhary
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectOUM SAOKOSAL
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methodsfarhan amjad
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objectsRai University
 
Object and class in java
Object and class in javaObject and class in java
Object and class in javaUmamaheshwariv1
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++Mohamad Al_hsan
 

Mais procurados (20)

Class and object in C++ By Pawan Thakur
Class and object in C++ By Pawan ThakurClass and object in C++ By Pawan Thakur
Class and object in C++ By Pawan Thakur
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Write First C++ class
Write First C++ classWrite First C++ class
Write First C++ class
 
Class or Object
Class or ObjectClass or Object
Class or Object
 
class c++
class c++class c++
class c++
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Java oop
Java oopJava oop
Java oop
 
Classes and objects1
Classes and objects1Classes and objects1
Classes and objects1
 
Java chapter 4
Java chapter 4Java chapter 4
Java chapter 4
 
Advanced data structures using c++ 3
Advanced data structures using c++ 3Advanced data structures using c++ 3
Advanced data structures using c++ 3
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
 
Classes, objects and methods
Classes, objects and methodsClasses, objects and methods
Classes, objects and methods
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Java unit2
Java unit2Java unit2
Java unit2
 
Object and class in java
Object and class in javaObject and class in java
Object and class in java
 
object oriented programming language by c++
object oriented programming language by c++object oriented programming language by c++
object oriented programming language by c++
 
Object and class
Object and classObject and class
Object and class
 
OOP
OOPOOP
OOP
 
Java basic understand OOP
Java basic understand OOPJava basic understand OOP
Java basic understand OOP
 

Destaque

C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsakreyi
 
Web-программирование и жизнь.
Web-программирование и жизнь.Web-программирование и жизнь.
Web-программирование и жизнь.Alex Mamonchik
 
Обобщенные классы в C#
Обобщенные классы в C#Обобщенные классы в C#
Обобщенные классы в C#REX-MDK
 
Лекция #6. Введение в Django web-framework
Лекция #6. Введение в Django web-frameworkЛекция #6. Введение в Django web-framework
Лекция #6. Введение в Django web-frameworkЯковенко Кирилл
 
Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)mujeeb memon
 
Основы ооп на языке C#. Часть 2. базовый синтаксис.
Основы ооп на языке C#. Часть 2. базовый синтаксис.Основы ооп на языке C#. Часть 2. базовый синтаксис.
Основы ооп на языке C#. Часть 2. базовый синтаксис.YakubovichDA
 
основы ооп на языке C#. часть 1. введение в программирование
основы ооп на языке C#. часть 1. введение в программированиеосновы ооп на языке C#. часть 1. введение в программирование
основы ооп на языке C#. часть 1. введение в программированиеYakubovichDA
 
Лекция #4. Каскадные таблицы стилей
Лекция #4. Каскадные таблицы стилейЛекция #4. Каскадные таблицы стилей
Лекция #4. Каскадные таблицы стилейЯковенко Кирилл
 
10 tips for learning Russian
10 tips for learning Russian10 tips for learning Russian
10 tips for learning RussianSteve Kaufmann
 

Destaque (11)

C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Web-программирование и жизнь.
Web-программирование и жизнь.Web-программирование и жизнь.
Web-программирование и жизнь.
 
Обобщенные классы в C#
Обобщенные классы в C#Обобщенные классы в C#
Обобщенные классы в C#
 
Лекция #6. Введение в Django web-framework
Лекция #6. Введение в Django web-frameworkЛекция #6. Введение в Django web-framework
Лекция #6. Введение в Django web-framework
 
Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)
 
Основы ооп на языке C#. Часть 2. базовый синтаксис.
Основы ооп на языке C#. Часть 2. базовый синтаксис.Основы ооп на языке C#. Часть 2. базовый синтаксис.
Основы ооп на языке C#. Часть 2. базовый синтаксис.
 
основы ооп на языке C#. часть 1. введение в программирование
основы ооп на языке C#. часть 1. введение в программированиеосновы ооп на языке C#. часть 1. введение в программирование
основы ооп на языке C#. часть 1. введение в программирование
 
Лекция #4. Каскадные таблицы стилей
Лекция #4. Каскадные таблицы стилейЛекция #4. Каскадные таблицы стилей
Лекция #4. Каскадные таблицы стилей
 
Programming in c
Programming in cProgramming in c
Programming in c
 
10 tips for learning Russian
10 tips for learning Russian10 tips for learning Russian
10 tips for learning Russian
 

Semelhante a C++ classes tutorials

C++ Classes Tutorials.ppt
C++ Classes Tutorials.pptC++ Classes Tutorials.ppt
C++ Classes Tutorials.pptaasuran
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their AccessingMuhammad Hammad Waseem
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#ANURAG SINGH
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-exampleDeepak Singh
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsRai University
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6sotlsoc
 
Lecture-03 _Java Classes_from FAST-NUCES
Lecture-03 _Java Classes_from FAST-NUCESLecture-03 _Java Classes_from FAST-NUCES
Lecture-03 _Java Classes_from FAST-NUCESUzairSaeed18
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined MethodPRN USM
 
Chapter19 constructor-and-destructor
Chapter19 constructor-and-destructorChapter19 constructor-and-destructor
Chapter19 constructor-and-destructorDeepak Singh
 
Csphtp1 09
Csphtp1 09Csphtp1 09
Csphtp1 09HUST
 

Semelhante a C++ classes tutorials (20)

Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
C++ classes
C++ classesC++ classes
C++ classes
 
C++ Classes Tutorials.ppt
C++ Classes Tutorials.pptC++ Classes Tutorials.ppt
C++ Classes Tutorials.ppt
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
 
UNIT I (1).ppt
UNIT I (1).pptUNIT I (1).ppt
UNIT I (1).ppt
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#
 
Chapter22 static-class-member-example
Chapter22 static-class-member-exampleChapter22 static-class-member-example
Chapter22 static-class-member-example
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
oop objects_classes
oop objects_classesoop objects_classes
oop objects_classes
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
Chapter 6.6
Chapter 6.6Chapter 6.6
Chapter 6.6
 
Lecture-03 _Java Classes_from FAST-NUCES
Lecture-03 _Java Classes_from FAST-NUCESLecture-03 _Java Classes_from FAST-NUCES
Lecture-03 _Java Classes_from FAST-NUCES
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Chapter19 constructor-and-destructor
Chapter19 constructor-and-destructorChapter19 constructor-and-destructor
Chapter19 constructor-and-destructor
 
Lecture09
Lecture09Lecture09
Lecture09
 
3433 Ch09 Ppt
3433 Ch09 Ppt3433 Ch09 Ppt
3433 Ch09 Ppt
 
Csphtp1 09
Csphtp1 09Csphtp1 09
Csphtp1 09
 

Último

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 

Último (20)

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

C++ classes tutorials

  • 1. C++ Classes & Object Oriented Programming
  • 2. Object Oriented Programming  Programmer thinks about and defines the attributes and behavior of objects.  Often the objects are modeled after real- world entities.  Very different approach than function-based programming (like C).
  • 3. Object Oriented Programming  Object-oriented programming (OOP) – Encapsulates data (attributes) and functions (behavior) into packages called classes.  So, Classes are user-defined (programmer- defined) types. – Data (data members) – Functions (member functions or methods)  In other words, they are structures + functions
  • 4. Classes in C++  A class definition begins with the keyword class.  The body of the class is contained within a set of braces, { } ; (notice the semi-colon). class class_name Any valid } identifier .… .… Class body (data member .… + methods) methods ;{
  • 5. ++Classes in C  Within the body, the keywords private: and public: specify the access level of the members of the class. – the default is private.  Usually, the data members of a class are declared in the private: section of the class and the member functions are in public: section.
  • 6. Classes in C++ class class_name } :private private members or … methods … … public: … Public members or methods … … ;{
  • 7. Classes in C++  Member access specifiers – public:  can be accessed outside the class directly. – The public stuff is the interface. – private:  Accessible only to member functions of class  Private members and methods are for internal use only.
  • 8. Class Example  This class example shows how we can encapsulate (gather) a circle information into one package (unit or class) No need for others classes to class Circle access and retrieve its value directly. The { class methods are responsible for private: that only. double radius; public: void setRadius(double r); They are accessible from outside double getDiameter(); the class, and they can access the double getArea(); member (radius) double getCircumference(); };
  • 9. Creating an object of a Class  Declaring a variable of a class type creates an object. You can have many variables of the same type (class). – Instantiation  Once an object of a certain class is instantiated, a new memory location is created for it to store its data members and code  You can instantiate many objects from a class type. – Ex) Circle c; Circle *c;
  • 10. Special Member Functions  Constructor: – Public function member – called when a new object is created (instantiated). – Initialize data members. – Same name as class – No return type – Several constructors  Function overloading
  • 11. Special Member Functions class Circle Constructor with no { argument private: double radius; public: Constructor with one Circle(); argument Circle(int r); void setRadius(double r); double getDiameter(); double getArea(); double getCircumference(); };
  • 12. Implementing class methods  Class implementation: writing the code of class methods.  There are two ways: 1. Member functions defined outside class  Using Binary scope resolution operator (::)  “Ties” member name to class name  Uniquely identify functions of particular class  Different classes can have member functions with same name – Format for defining member functions ReturnType ClassName::MemberFunctionName( ){ … }
  • 13. Implementing class methods 2. Member functions defined inside class – Do not need scope resolution operator, class name; class Circle { Defined private: inside double radius; class public: Circle() { radius = 0.0;} Circle(int r); void setRadius(double r){radius = r;} double getDiameter(){ return radius *2;} double getArea(); double getCircumference(); };
  • 14. class Circle { private: double radius; public: Circle() { radius = 0.0;} Circle(int r); void setRadius(double r){radius = r;} double getDiameter(){ return radius *2;} double getArea(); double getCircumference(); }; Circle::Circle(int r) { Defined outside class radius = r; } double Circle::getArea() { return radius * radius * (22.0/7); } double Circle:: getCircumference() { return 2 * radius * (22.0/7); }
  • 15. Accessing Class Members  Operators to access class members – Identical to those for structs – Dot member selection operator (.)  Object  Reference to object – Arrow member selection operator (->)  Pointers
  • 16. class Circle { private: double radius; public: The first Circle() { radius = 0.0;} The second constructor is Circle(int r); constructor is called void setRadius(double r){radius = r;} called double getDiameter(){ return radius *2;} double getArea(); void main() Since radius is a double getCircumference(); { private class data }; Circle c1,c2(7); member Circle::Circle(int r) { cout<<“The area of c1:” radius = r; <<c1.getArea()<<“n”; } double Circle::getArea() //c1.raduis = 5;//syntax error { c1.setRadius(5); return radius * radius * (22.0/7); cout<<“The circumference of c1:” } << c1.getCircumference()<<“n”; double Circle:: getCircumference() { cout<<“The Diameter of c2:” return 2 * radius * (22.0/7); <<c2.getDiameter()<<“n”; } }
  • 17. class Circle { private: double radius; public: Circle() { radius = 0.0;} Circle(int r); void setRadius(double r){radius = r;} double getDiameter(){ return radius *2;} double getArea(); double getCircumference(); }; Circle::Circle(int r) void main() { { Circle c(7); radius = r; Circle *cp1 = &c; } Circle *cp2 = new Circle(7); double Circle::getArea() { cout<<“The are of cp2:” return radius * radius * (22.0/7); <<cp2->getArea(); } double Circle:: getCircumference() } { return 2 * radius * (22.0/7); }
  • 18. Destructors  Destructors – Special member function – Same name as class  Preceded with tilde (~) – No arguments – No return value – Cannot be overloaded – Before system reclaims object’s memory  Reuse memory for new objects  Mainly used to de-allocate dynamic memory locations
  • 19. Another class Example  This class shows how to handle time parts. class Time { private: int *hour,*minute,*second; public: Time(); Time(int h,int m,int s); void printTime(); void setTime(int h,int m,int s); int getHour(){return *hour;} int getMinute(){return *minute;} Destructor int getSecond(){return *second;} void setHour(int h){*hour = h;} void setMinute(int m){*minute = m;} void setSecond(int s){*second = s;} ~Time(); };
  • 20. Time::Time() { hour = new int; minute = new int; second = new int; *hour = *minute = *second = 0; } Dynamic locations Time::Time(int h,int m,int s) should be allocated { to pointers first hour = new int; minute = new int; second = new int; *hour = h; *minute = m; *second = s; } void Time::setTime(int h,int m,int s) { *hour = h; *minute = m; *second = s; }
  • 21. void Time::printTime() { cout<<"The time is : ("<<*hour<<":"<<*minute<<":"<<*second<<")" <<endl; } Destructor: used here to de- Time::~Time() allocate memory locations { delete hour; delete minute;delete second; } void main() Output: { Time *t; The time is : (3:55:54) t= new Time(3,55,54); The time is : (7:17:43) t->printTime(); Press any key to continue t->setHour(7); t->setMinute(17); t->setSecond(43); t->printTime(); When executed, the destructor is called delete t; }
  • 22. Reasons for OOP 1. Simplify programming 2. Interfaces  Information hiding: – Implementation details hidden within classes themselves 3. Software reuse  Class objects included as members of other classes