C++ 25: Reference Variables, Copy Constructors
Reference Variables:
A refrence variable is used to provide an alternate name (i.e. alis) for an existing variable or object.
Syntax:
data_type &ref_name = existing_variable
#include <iostream>
using namespace std;main(){ int a = 10; int &b = a; int &c = b;
cout << "Address of a = " << &a << endl; cout << "Address of b = d" << &b << endl; cout << "Address of c = " << &c << endl;
printf("Address of a is %u\n", &a); printf("Address of b is %u\n", &b); printf("Address of c is %u\n", &c);
cout << "a =" << a << " b = " << b << " c=" << c << endl;}
Output:
Address of a = 0x61fe0c
Address of b = d0x61fe0c
Address of c = 0x61fe0c
Address of a is 6422028
Address of b is 6422028
Address of c is 6422028
a =10 b = 10 c=10Copy Constructors
- Copy constructors is used to initialize an object by using data of another object of same class.
- The copy constructors takes reference of an object as argument.
- A copy constructor is atomically called when we pass an object while creating another object of same class or if we assign an object
- while creating another object of same class.
- 4.Remember that the copy constructor, assignment operator function and this pointer is atomically added in the class during compilation process.
Syntax:
class_name(class_name &ref_obj)
{
....
....
}
Example:
#include <iostream>
using namespace std;class Distance{private: int F, I;
public: Distance(int i, int f) { I = i; F = f; } Distance(Distance &p) //Copy Constructor { F = p.I; I = p.I; } void showData() { cout << "Distance is" << F << " feet and " << I << "inches." << endl; }};main(){ Distance a(5, 2); a.showData();
Distance b(a); //Copy constructor will invoke b.showData();
Distance c = b; //Copy constructor will invoke c.showData();}
Output:
Distance is2 feet and 5inches.
Distance is5 feet and 5inches.
Distance is5 feet and 5inches.Scope Resolution Operator ( :: )
Uses:
- To acess the global variable when local and global variables have same name.
- To define the member functions outside the class
- To assign value to static dta men=mber
- To call static member functions
- To call base class overrided function in derived class during the process of inheritance.
#include <iostream>
using namespace std;int a = 10;
main(){ int a = 5; //local variable cout << "a = " << a << endl; cout << "a(global) = " << ::a << endl;}Output:
a = 5
a(global) = 10
Comments
Post a Comment