Logo 
Search:

C++ Programming Articles

Submit Article
Home » Articles » C++ Programming » BeginnersRSS Feeds

Classes and Objects

Posted By: Ella Campbell     Category: C++ Programming     Views: 26101

This article explains about Limitations of and Extension to Structs, Class, Private and Public Members of Class, Inside and Outside Definition of Member Functions, Nesting of Member Functions, Arrays and Memory Allocation, Static Variable, Static Class Member, Static Functions, Arrays of Objects, Objects As Function Arguments, Friend Function, Characteristics of a Friend, Friend Function From Other Class, Returning Objects and Const Members, Pointer to Members, Pointer to Members, Pointer to Function, Pointer to Member Function.

Limitations of and Extension to Structs

  • Defining complex variables does not allow us to add them
  • Struct variables are globally available
  • In C++ structures can have both functions and data as members which can be hidden also
  • Declaration does not require struct keyword
  • Class & struct are same, default status of class members is private while in structure it’s public
  • Programmers do not use structs to hold funs

Class

  • The class definition and the function definition
  • The similarity with struct
  • The abstract type data of class name and the instance of class, i.e. objects 
  • The private and public members
  • Data members and member functions
  • Creation of object and similarity with the built-in type with the user-defined type
  • Methods as functions

Private and Public Members of Class


Inside and Outside Definition of Member Functions

 class item
 {     int number; //private by default
        float cost;
  public :
         void getdata(int a, float b); (declaration)
         void putdata(void); (definition, inline)
         { cout << number << endl;
            cout << cost << endl;}
  }; 
 void item::getdata(int a, float b)
  { number = a; cost = b; }

Nesting of Member Functions

 class set 
 {  int m, n;
    public :
      void input(void);
      void display(void);
      int largest(void);
  };
 void set :: largest() // can be made private
   { return (m>n) ? m : n }
 void set :: display(void)
 { cout << “largest value is ” << largest(); }

Arrays and Memory Allocation

  • Arrays can be defined and used as if it can be used in a c struct
  • Memory allocation for member functions is done at the time of definition 
  • When the object is created, the space for member variable is allocated
  • Static data variable hold the same status as C
  • Only one copy of that variable is created for many instances, so only once MA is made

Static Variable

  • Static variables are initialized to zero when defined, no other initialization is permitted
  • It is visible only within a class, but the life time is the entire program
  • Static data members are stored separately rather than part of an object
  • Type and scope of each static variable must be defined outside the class definition
  • They are known as class variables

Static Class Member : Example

 class item
  { static int count;
     int number;
  public :
    void getcount(void)
     { cout << “ count is “ << count; }
  };
 int item :: count;
 main ()
 { item a, b, c;
   a.getcount(); b.getcount(); c.getcount(); }

Static Functions

  • Static function can have access to only other static members declared in the same class
  • A static member function can be called using class name :: function name
  • Making it work without static function, we need a dummy object to be created and used
  •  static void getcount() is defined in the class
  •  item::getcount() is the call to the getcount
  • There is no need to create any dummy object!

Arrays of Objects

class employee
  { char name[30];
     float age;
public : 
    void getdata(void);
    void putdata(void);    }
employee manager[3];       //Defining arrays
employee foreman[15]; // space for only data items
employee worker[75];  // of the object are created
manager[i].putdata();  // working with an element

Objects As Function Arguments

  • Pass by value and reference(address)
  • pass by reference is more efficient but more dangerous as well
  • The object of the method being called is passed implicitly
  • An object can also be passed to a non member function
  • Such functions can only have an access to the public member functions of the passed objects


Example

#include <iostream.h>
class time
{ int hours, minutes;
   public : 
   void gettime(int h, int m) {hours=h; minutes=m;}
  void puttime() {cout << “hours ”<< hours;
                            cout << “time” << time; }
  void sum(time,time);  // objects are arguments
  };  

void time :: sum(time t1,time t2)
{minutes = t1.minutes + t2.minutes;
  hours = minutes /60;   minutes = minutes%60;
  hours = hours + t1.hours +t2.hours; }

main()
{ time t1,t2,t3;
   t1.gettime(2,45);
   t2.gettime(3,30);

   t3.sum(t1,t2);

   cout << “t1 =“; t1.puttime();
   cout << “ t2 = “; t2.puttime();
   cout << “t3 = “ ; t3.puttime();
 }  

Friend Function

class sample
{ int a,b;
   public :
     void setvlaue() { a = 25; b = 20; }
     friend float mean (sample s);
 };
float mean (sample s) { return float (s.a+s.b)/2.0; }
main ()
{ sample X;
  X.setvalue();
  cout << “ Mean Value is =“ << mean(X) <<“\n”;}

Characteristics of a Friend

  • It is not the in the scope of the class to which it has been declared as friend
  • It can not be called using the object of the same class, only invoked like a normal function
  • It can not access the member names directly, it has to use object.member name for that
  • It can be declared in either public or private area
  • Usually it has the objects as arguments
  • Departure from the OO methodology 
  • Member friend of one class can be a friend of some other class
  • A class (X) can be a friend of another class(Z)!
  • i.e. all member functions of X are friends to Z
  • Friendship is not two way here
  • A friend can act as a bridge between two different classes
  • A friend function called by reference can work directly on objects

Friend Function From Other Class

class Y;
class X
{ int fun1(class Y, Class Y);};//public function!
class Y
{int a,b;
  friend int X::fun1();};
// friend class X can also be used
main ()
 { X xobj; Y y1,y2;
    xobj.fun1(y1,y2) }

Returning Objects and Const Members

  • Functions can return objects as any other variable
  • Function can return objects by defining a temp object and assigning values to it 
  • They can also return unnamed objects
  • They can also return a reference to an object
  • If a member function does not alter any data in the class then it can declared as follows
  • void mul(int,int) const;     // const is appended to
  • double GetBallance() const; // def and dec both

Pointer to Members

  • Applying the & operator to Fully Qualified class member name yields the address of a member
  • A class member pointer can be declared using ::* operator as  follows
class A
{ private : int m;
   public : void show(); }
int A::* p =& A::m           // instead of *p = m
cout << a.*p;          // display same as below
cout << a.m;         // for a, an object of A class

Pointer to Object and Member

ap = &a //ap is pointer to object a
cout << ap ->*p  //display m
cout << ap ->m  // display m
  • The dereferencing operator ->* is used to access a member when we use pointer to both of them
  • The dereferencing operator ->. is used to access a member when use object with member pointer
  • Note that *p is used as a member name
  • Pointers to member functions can also be invoked using dereferencing operators

Pointer to Function 

main()
{
   double y(), cos(), table();
   table (y,0.0,2.0,0.5); //print y values
   table (cos,0.0,3.1415,0.5);} // print cos values
   double (double (*f)(),min,max,step;)
  {
      double a, value;
      for (a=min;a,=max; a+=step)
      {
          value = (*f)(a);
          printf(“%5.2f %10.4f\n”,a,value);} 
       }
    double y (double x) 
    {return (2*x*x-x+1);}

Example : Pointer to Member Function

class M
    int x,y;
    public : getvalues(int a, int b) { x =a ; y = b}
    friend int sum (M m); 
};
int sum(M m)
    int M ::* px = &M :: x;   
    int M ::* py = &M :: y; 
    M *op = &m;
    int s= m.*px + pm ->*py; 
    return s;
}
main()
    int (M ::*pf) (int , int) = &M :: getvalues;
    M n; (n.*pf)(10,20);
    M *op = &n; (op->*pf) (30,40);
  
Share: 

 
 

Didn't find what you were looking for? Find more on Classes and Objects Or get search suggestion and latest updates.

Ella Campbell
Ella Campbell author of Classes and Objects is from Toronto, Canada.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!