Posts

c++ referance , how it is different from pointer

References in C++ When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration . #include<iostream>  using namespace std;  int main()  {  int x = 10;  // ref is a reference to x.  int& ref = x;  // Value of x is now changed to 20  ref = 20;  cout << "x = " << x << endl ;  // Value of x is now changed to 30  x = 30;  cout << "ref = " << ref << endl ;  return 0;  }  Output: x = 20 ref = 30 References vs Pointers Both references and pointers can be used to change local variables of one function inside another function. Both of them can also be used to save copying of big objects when passed as arguments to functions or returned from functions, to get efficiency gain. Despite above similarities, there ar...

Virtual Functions and Runtime Polymorphism in C++

Image
Consider the following simple program which is an example of runtime polymorphism. The main thing to note about the program is, derived class function is called using a base class pointer. The idea is,  virtual functions  are called according to the type of object pointed or referred, not according to the type of pointer or reference. In other words, virtual functions are resolved late, at runtime. #include<iostream> using namespace std;      class Base { public :      virtual void show() { cout<< " In Base \n" ; } };      class Derived: public Base { public :      void show() { cout<< "In Derived \n" ; } };      int main( void ) {      Base *bp = new Derived;      bp->show();  // RUN-TIME POLYMORPHISM      return 0; } Output: In Derived What is ...