Showing posts with label advanced. Show all posts
Showing posts with label advanced. 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

Sunday, February 3, 2013

Average of 5 Number using vector in c++

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<int> grades;   //declaration of vector
    int grade, total;
    double average;
    total = 0;
   
    for(int i=1; i<=5; ++i)        //Taking the input from user
    {
        cout << "Enter a grade: ";
        cin >> grade;
        grades.push_back(grade);
    }
   
    for(int i = 0; i < grades.size(); ++i)
    {
        //cout << grades[i] << " ";
        total += grades[i];
    }
    
    average = total / grades.size();
    cout << "the average is " << average << endl;
    
    return 0;
}


OUTPUT:

A vector<int> (meaning 'a vector of ints') in much the same way as you would use an ordinary C array, except that vector eliminates the chore of managing dynamic memory allocation by hand.

vector<int> v(3); // Declare a vector (of size 3 initially) of ints
     v[0] = 7;
     v[1] = v[0] + 3;
     v[2] = v[0] + v[1]; // v[0] == 7, v[1] == 10, v[2] == 17
     v.push_back(13); // add another element - the vector has to expand

Note the use of the push_back function - adding elements this way will make the container expand.

Remember that:

1. vector elements can move! insert, for instance, changes its 1st argument.
2. vector doesn't have arithmetic operations: valarray (which is described
later) does. p.51
3. vector doesn't have range-checking by default.

Friday, January 25, 2013

A note on Command line argument

Arguments can be passed to any function in a program, including the main() function.

Arguments passed to main(), must be declared as part of the function’s definition. To standardize passing arguments to a main() function, only two  items are allowed: a number and an array. The number is an integer variable, typically named argc (short for argument counter), and the array is a one-dimensional list, which is, by convention, named argv (short for argument values). Figure D.3 illustrates these two arguments.
----------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    int i;
   
    cout << "\n The number of items on the command line is "
         << argc << endl << endl;
       
    for(i = 0; i < argc; i++)
    {
        cout << "the address stored in argv[" << i << "] is "
             << int (argv[i]) << endl; //dispaly address as an integer number
           
        cout << "the character pointed to is " << *argv[i] << endl;
    }
   
    return 0;
}

OUTPUT:
 ____________________________________________________________

 // A program that displays its command-line arguments

#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
    int i;
    cout << "\nThe following arguments were passed to main(): ";
   
    for (i = 0; i < argc; i++)
    {
        cout << argv[i] << " ";
    }
   
    cout << endl;
    return 0;
}

OUTPUT:
 

Monday, January 21, 2013

Write a program to swap 2 numbers using bitwise operators

//Write a program to swap 2 number without arithmetic operator

#include <stdio.h>

int main()
{
    int i=65;
    int k=120;
   
    printf("\n value of i=%d k=%d before swapping",i,k);
    i = i^k;
    k = i^k;
    i = i^k;
   
    printf("\n value of i=%d k=%d after swapping",i,k);
    return 0;
}


OUTPUT:

Wednesday, January 16, 2013

Smart Pointer (works as garbage collection) in c++

//smart (auto) pointer is a new feature of c++11
#include <memory>           //     <-- 0
#include <string>
using namespace std;

typedef auto_ptr<Car> CarPtr;


class Car{
    public:
        void startEngine()

        {
            //...................
        }
       
        void tuneRadioTo()

        {
            //...................
        }
};

void f()
{
  CarPtr p(new Car());         //    <-- 1
  p->startEngine();             //    <-- 2
  p->tuneRadioTo();            //    <-- 3
}                                    //    <-- 4

int main()
{
   f();
}
 

0: This gets the definition for auto_ptr
1: Create an object
2: Call a member function
3: Call another member function
4: Destroy the Car object

-----------------------------------------------------------------------------------------------

//Program to show drawback of auto pointer
#include <memory>             
#include <iostream>
using namespace std;

class Test{
    public:
        void print(){
            cout << "Test::print" << endl;
        }
};

int main(){
    auto_ptr<Test>  aptr1(new Test);
    aptr1 -> print();
   
    cout << aptr1.get();
   
    auto_ptr<Test>  aptr2(aptr1);
    aptr2 -> print();
   
    cout << aptr1.get();
    cout << aptr2.get();
   
    return 0;

}

OUTPUT:

To overcome this c++11 provide another mechanism called smart (shared) pointer.

Sunday, January 13, 2013

Virtual Inheritance

Virtual inheritance:
                        Inheritance can be private (where even the public fields of the base class are treated as private), public (where the base class determines visibility), or virtual. With virtual inheritance there is only one copy of each object even if (because of multiple inheritance) the object appears more than once in the hierarchy. In the following example, derived1a and derived1b each contain a base object, butderived2 contains just one field.

#include <iostream>
using namespace std;

class base{
    public:
        int i;
};

class derived1a: virtual public base {
    public:
        int j;
};

class derived1b: virtual public base {
    public:
        int k;
};

class derived2: public derived1a, public derived1b{
    public:
        int product(){
            return i*j*k;
        }
};

int main()
{
    derived2 obj;
    obj.i = 10;
    obj.j = 3;
    obj.k = 5;
   
    cout << "\n product is " << obj.product() << '\n';
    return 0;
}

OUTPUT:

Thursday, January 3, 2013

Simple Thread program using, Thread support library in c++

//thread is a new feature of c++11 standard

#include <iostream>
#include <thread>
using namespace std;

void threadFun()
{
    cout << "hi from thread \n";
}

int main()
{
    thread th(&threadFun);
    cout << "hi from main \n";
    th.join();
    return 0;
}


 

//this program to show parallel programming
// using lamda function


#include <iostream>
#include <thread>
using namespace std;

int main()
{
    thread th([]()
    {
        cout << "hi from thread \n";
    }
    );


    cout << "hi from main \n";
    th.join();
    return 0;
}


Run these program and see the beauty of thread. (most sexiest output you have ever seen before.)

Note: For thread library support in c++ you require latest complier
  • In linux GCC 4.6 or higher
  • In windows Visual c++ 2012 or MinGw64, (MinGw32 yet not able to compile thread program)

for further information see Thread support library.

Saturday, December 29, 2012

why use interfaces

So if an interface implements no functionality then why should we use them?
     Using interface based design concept provides loose coupling, component-based programming, easier maintainability, makes your code base more scalable and makes code reuse much more accessible because implementation is separated from the interface. Interfaces add a plug and play like architecture into your applications. Interfaces help define a contract (agreement or blueprint, however you chose to define it), between your application and other objects. This indicates what sort of methods, properties and events are exposed by an object.


This article not complete yet, we are in developing  phase, we are sorry

What are the 5 uses of delegate

1. Most important use of delegates- it helps us to define an abstract pointer which can point to methods and functions. The same abstract delegate can be later used to point to that type of functions and methods.

2. Callback mechanism Many times we would like to provide a call back mechanism. Delegates can be passed to the destination and destination can use the same delegate pointer to make callbacks.

3. Asynchronous processing By using ‘BeginInvoke’ and ‘EndInvoke’ we can call delegates asynchronously.

4. Multicasting - Sequential processing Some time we would like to call some methods in a sequential manner which can be done by using multicast delegate.

5. Events - Publisher subscriber modelWe can use events to create a pure publisher / subscriber model.


Code Project uses of delegate click here

Friday, November 30, 2012

Simple delegate program in c++

#include <iostream>
using namespace std;

int myFunction1(int x)
{
  return x + 10;
}

int myFunction2(int x)
{
  return x * 10;
}

int execFunction(int(*function)(int), int x)
{
  return function(x);
}

int main()
{
  int y = execFunction( myFunction1, 10 );
  cout << y << "\n";


  y = execFunction( myFunction2, 10 );
  cout << y << "\n";
  return 0;
}


OUTPUT: 

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

Thursday, November 22, 2012

What are Design Patterns

Design patterns are optimized, reusable solutions to the comman occouring problems in programming that we encounter every day. It’s not language-specific . Most importantly, any design pattern can be a double-edged sword— if implemented in the wrong place, it can be disastrous and create many problems for you. However, implemented in the right place, at the right time, it can be your savior.
            A design pattern is not a class or a library that we can simply plug into our system; it’s much more than that. It is a template that has to be implemented in the correct situation.

There are three basic kinds of design patterns:
  1. structural
  2. creational
  3. behavioral
Structural patterns generally deal with relationships between entities, making it easier for these entities to work together.

Creational patterns provide instantiation mechanisms, making it easier to create objects in a way that suits the situation.

Behavioral patterns are used in communications between entities and make it easier and more flexible for these entities to communicate.

Further Reading:
  1. Design Pattern at Dofactory.com
  2. Design pattern Wikipedia
  3. Design Pattern in C++
  4. Design Pattern Good Explaination 
  5. Design Pattern Another nice Examples 

Wednesday, November 21, 2012

Simple Thread Programming in C#

// creating and starting threads
using System;
using System.Threading;
public class AOne
{
    public void First()
    {
        Console.WriteLine("First methode of AOne class is running on T1 thread.");
        Thread.Sleep(1000);
        Console.WriteLine("The First method called by T1 thread has ended.");
    }
   
    public static void Second()
    {
        Console.WriteLine("First methode of AOne class is running on T1 thread.");
        Thread.Sleep(2000);
        Console.WriteLine("The First method called by T1 thread has ended.");
    }   
}

public class ThreadExp
{
    public static int Main(string[] args)
    {
        Console.WriteLine("Example of Threading");
        AOne a = new AOne();
        Thread T1 = new Thread(new ThreadStart(a.First));  //creating thread T1
        T1.Start();    //Strating thread T1
        Console.WriteLine("T1 thread  started.");
        Thread T2 = new Thread(new ThreadStart(AOne.Second));  //creating thread T2
        T2.Start();    //starting thread T2
        Console.WriteLine("T2 thread started.");
        return 0;
    }
}

_____________________________________________________________________________________

// 2nd Program------using timer
using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;

namespace ThreadTimers
{
    class Program
    {
        static void Main()
        {
            Timer time = new Timer();  //Doesn't require any args
            time.Interval = 1000;
            time.Elapsed += time_Elapsed;    //uses an event
            time.Start();      //start the timer
            Console.ReadLine();
            time.Stop();
            Console.WriteLine("Timer Thread stopped. Enter again to start. \n Twice entering would

                                                               destroy the thread.");              //pause the timer
            Console.ReadLine();
            time.Start();           //Resume the timer
            Console.ReadLine();
            Console.WriteLine("Thread destroyed!");
            time.Dispose(); //Destroy the timer Thread
        }
       
        static void Display(object ObjTime)
        {
            //This runs on a pooled thread            
            Console.WriteLine(ObjTime);            //Writes "tick..."
        }
       
        static void time_Elapsed (object sender, EventArgs e)
        {
            Console.Write("The Time is passing by: ");
            Console.WriteLine(DateTime.Now);
        }
    }
}

Tuesday, November 20, 2012

Standard Template Library: Algorithm

Algorithms (in <algorithm>) operate on containers, including strings. They may not always be the fastest option but they're often the easiest. They fall into 6 groups:
  1.  Search algorithms - search(), count_if(), etc.
  2.  Sorting algorithms - sort(), merge(), etc.
  3.  Deletion algorithms - remove(), unique(), etc.
  4.  Numeric algorithms - partial_sum(), inner_product(), etc.
  5.  Generation algorithms - generate(), for_each(), etc.
  6.  Relational algorithms - equal(), min(), etc.

Monday, November 19, 2012

Simple Thread program in c++

//Filename: SimpleThreadTest.cpp
#include <iostream>
#include <windows.h>
#include <process.h>
#include <time.h>

using namespace std;

void myThreadFunction(void *p)
{
  int n = (INT_PTR)p;
  Sleep(n * 1000);
  cout << "Ending Thread At: " << time(NULL) << endl;
}

int main(int argc, const char* argv[])
{
  cout << "Start Time: " << time(NULL) << endl;


  HANDLE myThread = (HANDLE)_beginthread(myThreadFunction, 0, (void*)5);


  WaitForSingleObject(myThread, 100000);
  return 0;
}


______________________________________________________________________________________

//Filename: SimpleMultiThreadTest.cpp

#include <iostream>
#include <windows.h>
#include <process.h>
#include <time.h>

using namespace std;

void myThreadFunction(void *p)
{
  int n = (INT_PTR)p;
  Sleep(n * 1000);
  cout << "Ending Thread At: " << time(NULL) << endl;
}

int main(int argc, const char* argv[])
{
  srand(time(NULL));
  const int threadSize = 5;
  HANDLE myThreads[threadSize];
  for(int i = 0; i < threadSize; i++)
      myThreads[i] = (HANDLE)_beginthread(myThreadFunction, 0, (void*)(rand() % 10 + 1));

  for(int i = 0; i < threadSize; i++)
      WaitForSingleObject(myThreads[i], 100000);
  return 0;
}

Monday, October 15, 2012

Advantages and disadvantages of inline function in c++

The purpose of inline functions is to insert the code of a called function at the point where the function is called.It can improve the application's performance but not always.If you have two or three statements then it works otherwise compiler will ignore inline keyword.

    We put inline keyword in front of a function which requests a compiler to make that function as inline function. When we call an inline function, it expands (similar to macro) itself and skipped from actual function call as in case of normal functions happen. Let’s take a small example.


inline int minimum (int x, int y)
{
      return x < y ? x: y;
}

int main()
{
      cout << “minimum of 50 and 70 is” << minimum (50, 70);
      return 0;
}

As we put inline keyword so the function is expanded like below at the time of invocation.

int main()
{
      cout <<“minimum of 50 and 70 is” << (50 < 70? 50: 70;
      return 0;
}

Pros:

1. It increases performance.
2. It is better than macros because it does type checking.

Cons:

1. Compiler often generates a lot of low level code to implement inline functions.
2. It is necessary to write definition for an inline function (compared to normal function) in every module (compilation unit) that uses it otherwise it is not possible to compile a single module independently of all other modules.
3. If we use many inline functions then executable size will also be increased.
4. Little bit it breaks encapsulation because it exposes the internal of the objects






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” ?