Showing posts with label oops. Show all posts
Showing posts with label oops. Show all posts

Monday, February 18, 2013

Interview question on Virtual Function

Que. Can a methode in base class which is declared as virtual be called  using the base class pointer which is pointing to a derived  class object?
 


#include <iostream>
using namespace std;

class B
{
    public:
        virtual void foo()
        {
            cout << "\n its from B" << endl;
        }
};

class D: public B
{
    public:
         void foo()
        {
            cout << "\n its from D" << endl;
        }
};

int main()
{
    B * b = new D();
    b->B::foo();
    b->foo();   //here parent class access the function of child class
//  b->D::foo();  //error -->'D' is not a base of 'B'
    delete b;
    b = 0;

//    D * d = new B;  //error --> invalid conversion from 'B*' to 'D*'
    return 0;
}


OUTPUT:

See in C# also CLICK HERE

Thursday, December 20, 2012

Program to show static variable not goes in the memory of object

#include <iostream>
using namespace std;

class laptop
{
    int first_int;           //size of int is 4 byte
    int second_int;       // Means size of this class is 8 Byte
};

class car
{
    static int first_int;
            int second_int;
};

int main()
{
    laptop dell;
    car santro;
   
    cout << sizeof(dell) << endl;
    cout << sizeof(santro) << endl;
}


OUTPUT:
8


This Program show static variable not goes in the memory of object static variable is the only belonging of class.

Saturday, December 15, 2012

Pointer with classes

Pointer with classes:
                           c++ supports dynamic binding which is one of the powerful features of object oriented programming. To achieve dynamic binding we require virtual functions, which is implemented by concept of pointers with classes and object. Here we discuss concept of pointer, after that we explain virtual function.

1.1 Pointer of objects:
                                Car * santro; (is a pointer to an object of class Car)
as it happened with datastructure, in order to refer directly to a member of an object pointed by a pointer we use the arrow operator (->) of indirection. here is an example with some possible combinations:

//Pointer to classes

#include <iostream>
using namespace std;

class CRectangle
{
    int width, height;

    public:
        void set_values (int, int);
        int area(void)
        {
            return (width * height);
        }
};

void CRectangle::set_values (int a, int b)
{
    width = a;
    height = b;
}

int main()
{
    CRectangle a, *b, *c;
    CRectangle *d = new CRectangle[2];
    b = new CRectangle;
    c = &a;
   
    a.set_values (1, 2);
    b->set_values (3, 4);
    d->set_values (5, 6);
    d[1].set_values (7, 8);
   
    cout << "\n      a area: " << a.area();
    cout << "\n    *b area: " << b->area();
    cout << "\n    *c area: " << c->area();
    cout << "\n d[0] area: " << d[0].area();
    cout << "\n d[1] area: " << d[1].area();
}

Polymorphism

Polymorphisms is a generic term that means 'many shapes'. More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.

WHY polymorphism:
1. it makes our code simple. (by giving polymorphic nature)
2. u don't have remember which methode to call.


Diffenrent type of polymorphism:
      1. Static Polymorphism (Early binding) [at compile time]
      2. Dynamic Polymorphism (Late binding) [at runtime]


Polymorphism:
    1.1 compile time polymorphism:
          1.1.1. operator overloading              
          1.1.2. funtion/methode overloading      
 

    1.2. runtime Polymorphism: 
           1.2.1 methode overriding

1. Pointer to classes

2. Array of pointer


3. This pointer


4. Virtual function


5. Abstract class and pure virtual function 1


6. Abstract class and pure virtual function 2


7. dynamic allocation and polymorphism

Tuesday, November 27, 2012

Journey through Function to Method ....part _2

sorry this article is still  in phase of development 
Method:
In object-oriented programming, a method is a subroutine (or procedure) associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time. Methods have the special property that at runtime, they have access to data stored in an instance of the class (or class instance or class object or object) they are associated with and are thereby able to control the state of the instance.The association between class and method is called binding. A method associated with a class is said to be bound to the class. Methods can be bound to a class at compile time (static binding) or to an object at runtime (dynamic binding).

·      1 Simple methods
·      2 Abstract methods
·      3 Accessor and mutator methods
·      4 Class methods
·      5 Conversion operator methods
·      6 Hook methods
·      7 Overloaded methods
·      8 Overridden methods
·      9 Special methods
·      9.1 Constructors
·      9.2 Destruction
·      9.3 Copy-assignment operators
·      9.4 Operator methods
·      10 Static methods
·      11 Virtual methods

Tuesday, October 30, 2012

What is Encapsulation

Notes from my guru Sandeep Karan sir.

Encapsulation [A information(data or implementation) hiding mechanism]

capsule means in plain english

  1. A structure that encloses a body part (function or class)
  2. A small container

Encapsulation is a process of binding data members (variables, properties) and member functions (methods, operation) into a single unit”. eg. Function And Class is the best example of encapsulation.

Encapsulation is a process of hiding all the internal details of an object(real entity, not class ka object) from the outside world.

The ultimate goal of Encapsulation is to achieve SIMPLICITY in our code.
__________________________________________________________________________
In “Students” Example let's Implement Encapsulation.
class Students          //No matter there is union or struct 

{
   public double totalMarks;              //data, variable or attribute
   public double MarksScored;

   
   public double GetPercentageMarks()      //operation
   {
       double Percentage =(MarksScored /totalMarks) * 100;
       return Percentage;
   }

}

Students ComputerStd = new Students(); 

In above code we have encapsulated totalMarks, MarksScored and method GetPercentageMarks. While creating a “ComputerStd” object, the implementation of GetPercentageMarks will not be shown.

________________________________________________________________________

Encapsulation
help us to achieve a rule of software enginerring called simplicity (and by simplicity we achieve maintainability & security)

  • encapsulation is achieved by class, function, delegate, property.
________________________________________________________________________
Function is also example of Encapsulation

void add()
{
    int a = 4;
    int b = 5;          //data, variable or attribute
    int  c;

    c =  a + b;       //operation

    cout << "Addtion of 2 no is: " << c;
}   
________________________________________________________________________


Advance definition:
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper. 
                                                        OR
In other words, encapsulation is the ability of an object to be a container (or capsule) for related properties (ie. data variables) and methods (ie. functions).             
                                                                                     OR
Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation                                                            (contractual--Relating to or part of a binding legal agreement)
==========================================================

Through encapsulation a class can hide the internal details of how an object does something. Encapsulation solves the problem at the implementation level.
      
    A class or structure can specify how accessible each of its members (variables, properties, and methods) is to code outside of the class or structure. Encapsulation simplifies the interaction between objects. An object can use another object without knowing all its data or how its data is maintained. For example, a Client object might have name, address, company, and department properties. If a Bank object wants to use a Client object, it can request the name and address for the bank without needing to know the company and department details of the Client object.
 
    With the help of encapsulation, a class can change the internal implementation without hurting the overall functionality of the system. Encapsulation protects abstraction.
_________________________________________________________________________
class Counter
{
    private int Count;

    public Counter()
    {
        Count = 0;
    }

    public void setCount( int newVal )
    {
        Count = newVal;
    }

    public int getCount()
    {
        return Count;
    }
}

This piece of code is also encapsulated, showing that you can have encapsulation without data hiding, but you cannot have data hiding without encapsulation.
____________________________________________________________________________ 
Now consider the function Substring() which returns the string based on the start index and length. The underlying algorithm and the internal data structures used to find the substring is specific to the String class and hidden from the external code who makes use of Substring() in which case the external code does not have previliges to modify the algorithm or the datastructures which are internal to (or encapsulated in) String class. This is known as encapsulation.
____________________________________________________________________________ 

Links to understand encapsulation: 

Thursday, October 11, 2012

What is a CLASS

class is a keyword or mechanism which used to create user-defined datatype or we can say that a comprehensive.
  • data type, which represents a blue-print of objects.
  • A class is like a template.
A class is composed of a set of data members and a set of operations that can be performed on the data.
A class defines the characteristics of an object.
characteristics include: 
1. Attributes                                     |car
   (data fields --> properties)             |[year, make, model, color, numbers of doors, engine] 

2. behaviors                                     |
   (
operation --> methods or fun.)        |[on(), off(), changes(), accelerate(), turn(), break()]


Note: Here, Properties means characteristic of  object or entity (thing).

         Don't get confused Property which is a concept in oops.
______________________________________________________________________
          public class Students
          {

               /*--code------*/
          }
          Students BiologyStd  = new Students();
          Students ComputerStd = new Students(); 


In our above example “Students” is a Class
which has objects “Biology Students” &  “Computer Students”.
_____________________________________________________________________
Note: class in c# by default reference type while in c++ it is valued type.



A class is composed of a set of data members and a set of operations that can be performed on the data.
Class rectangle

{

      private:                     |  //we can use private, public and protected,  (internal in c#)

                  int x;               |  set of data member

                  int y;                |  //data members are private by default



        public:                                           | this is set of operation
                 void set_values (int, int);   | //1st function (only declaration)
                 int area ()                             | //2nd function (with definition)
                 {                                             | //function must be public
                      return (x*y);                     |
                 }                                             |
};

In C++, a class type can be declared with the keywords union, struct, or class.

·         The members of a class declared with the keyword class are private by default. A class is inherited privately by default.
·      The members of a class declared with the keyword struct are public by default. A structure is inherited publicly by default.
·      The members of a union (declared with the keyword union) are public by default. A union cannot be used as a base class in derivation.
__________________________________________________________________________________
class X
{
     /* define class members here */
};
int main()
{
      X xobject1;       // create an object of class type X
      X xobject2;       // create another object of class type X
}
You may have polymorphic classes in C++. Polymorphism is the ability to use a function name that appears in different classes (related by inheritance), without knowing exactly the class the function belongs to, at compile time.

concepts related to C++ Classes and Objects, discuss below
Concept
Description
Class member functions
A member function of a class is a function that has its definition or its prototype within the class definition like any other variable.
Class access modifiers
A class member can be defined as public, private or protected. By default members would be assumed as private.
Constructor & destructor
A class constructor is a special function in a class that is called when a new object of the class is created. A destructor is also a special function which is called when created object is deleted.
C++ copy constructor
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.
C++ friend functions
A friend function is permitted full access to private and protected members of a class.
C++ inline functions
With an inline function, the compiler tries to expand the code in the body of the function in place of a call to the function.
The this pointer in C++
Every object has a special pointer this which points to the object itself.
Pointer to C++ classes
A pointer to a class is done exactly the same way a pointer to a structure is. In fact a class is really just a structure with functions in it.
Static members of a class
Both data members and function members of a class can be declared as static.

·         Classes not only include information regarding the real world object, but also functions to access the data, and classes possess the ability to inherit from other classes.
·         A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions.
·         An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.
·         Remember : A class is a type, and an object of this class is just a variable.

Classes are generally declared using the keyword class, with the following format:
class class_name {
  access_specifier_1:    //please notice : these colon
    member1;
  access_specifier_2:
    member2;
  ...
  } object_names;

Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this class. The body of the declaration can contain members, that can be either data or function declarations, and optionally access specifiers.

All is very similar to the declaration on data structures, except that we can now include also functions and members, but also this new thing called access specifier. An access specifier is one of the following three keywords: private, public or protected. These specifiers modify the access rights that the members following them acquire:
·      private members of a class are accessible only from within other members of the same class or from their friends.
·      protected members are accessible from members of their same class and from their friends, but also from members of their derived classes.
·      Finally, public members are accessible from anywhere where the object is visible.








class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area (void);
  } rect;
Declares a class (i.e., a type) called CRectangle and an object (i.e., a variable) of this class called rect. This class contains four members: two data members of type int (member x and member y) with private access (because private is the default access level) and two member functions with public access: set_values() and area(), of which for now we have only included their declaration, not their definition.

// classes example
#include <iostream>
using namespace std;

class CRectangle {
    int x, y;
  public:
    void set_values (int,int);  //prototype
    int area ()
    {
      return (x*y);
    }
};

void CRectangle::set_values (int a, int b) {
  x = a;
  y = b;
}

int main ()
{
  CRectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
  return 0;
}
The most important new thing in this code is the operator of scope (::, two colons) included in the definition of set_values(). It is used to define a member of a class from outside the class definition itself.

You may notice that the definition of the member function area() has been included directly within the definition of the CRectangle class given its extreme simplicity, whereas set_values() has only its prototype declared within the class, but its definition is outside it. In this outside definition, we must use the operator of scope (::) to specify that we are defining a function that is a member of the class CRectangle and not a regular global function.
The only difference between defining a class member function completely within its class or to include only the prototype and later its definition, is that in the first case the function will automatically be considered an inline member function by the compiler, while in the second it will be a normal (not-inline) class member function, which in fact supposes no difference in behavior.

 


Interview question: why u want to make class?
Answer: 1). better organization of data.
                    --give its a logical entity
                    --In class we all declared variable have a continues memory location
                    --class gives us grouping of variable in one place.
                    --by organise we achieve –maintainbility, security, efficiency.
2). Safety of data (private or protected)
3). Reusability (via inheritance)
4). Polymorphism (see above)
5). abstraction

Analogy:
         If a class is a house, then the functions will be the doors and the variables will be the items inside the house.

Class help us to achieve encapsulation:
If a class is a house, then the functions will be the doors and the variables will be the items inside the house. The functions usually will be the only way to modify the variables in this structure, and they are usually the only way even to access the variables in this structure. This might seem silly at first, but the idea to make programs more modular - the principle itself is called "encapsulation". The key idea is that the outside world doesn't need to know exactly what data is stored inside the class--it just needs to know which functions it can use to access that data. This allows the implementation to change more easily because nobody should have to rely on it except the class itself.

Constructor and destructor:
            Classes must always contain two functions: a constructor and a destructor. The syntax for them is simple: the class name denotes a constructor, a ~ before the class name is a destructor.
            When the programmer declares an instance of the class, the constructor will be automatically called. The only time the destructor is called is when the instance of the class is no longer needed--either when the program ends, the class reaches the end of scope, or when its memory is deallocated using delete
            Keep in mind that neither constructors nor destructors return arguments! This means you do not want to (and cannot) return a value in them.
            Note that you generally want your constructor and destructor to be made public so that your class can be created! The constructor is called when an object is created, but if the constructor is private, it cannot be called so the object cannot be constructed. This will cause the compiler to complain.

// example: class constructor
#include <iostream>
using namespace std;

class CRectangle
{
    int width, height;
  public:
    CRectangle (int,int);
    int area ()
    {
      return (width*height);
    }
};

CRectangle::CRectangle (int a, int b) 
{
  width = a;
  height = b;
}

int main ()
{
  CRectangle rect (3,4);
  CRectangle rectb (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
  return 0;
}
You can  see how neither the constructor prototype declaration (within the class) nor the latter constructor definition include a return value; not even void.


Question. What is the difference between “C++ class” and “C# class” ?