CPP QuickReference – From Novice to Expert- Level3

Level:3 MediumHigh

CPP QuickReference – From Novice to Expert- Level3

Welcome back,

This is the Level 3 of our Cpp Quick reference – From Novice to Expert.

Lets get inside

LEVEL : 3 | MEDIUM HIGH

50. C++ Object Oriented Programming _ Introducing Classes, Objects :

#include <iostream>
using namespace std;

class Device{ //class is a userdefined datatype,just a blueprint
private:   //access specifier
int id;    //attribute or property

public:
void setid(int iid){      //method or function to access the property
    id=iid;
}

void getid(){      //method or function
    cout<<id<<endl;
}
};

int main()
{
    Device d;//object(runtime variable of the class)
    d.setid(123);//accessing the member of class
    d.getid();//Dot operator to access members
    return 0;
}

51. C++ OOPS _ Class Properties, Methods, Members :

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

class Device{
public:
string name;

void detect(){
cout<<name<<" device detected"<<endl;
}
};

int main()
{
    Device bt;
    bt.name="bluetooth";
    bt.detect();
    
    Device wf;
    wf.name="Wifi";
    wf.detect();
    
    return 0;
}

52. Creating Objects from a Class in Different Ways _ C++ Object Oriented Programming :

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

class Device{
public:
string name;

void detect(){
cout<<name<<" device detected"<<endl;
}
};

int main()
{
    Device bt; //object stored in STACK
    bt.name="bluetooth";//use DOT OPERATOR to access object
    bt.detect();

    Device *wf=new Device();//object stored in HEAP,since dyn mem alloc
    wf->name="Wifi"; //use ARROW OPERATOR to access object , since its pointer
    wf->detect();

    return 0;
}

53. Scope Resolution Operator _ Defining Methods outside Class definition :

#include<iostream>
using namespace std;

class Device{
public:
    int id;//member variable can be initialized inside class, to be clarified
    /*Note: STATIC VARIABLES can be initialized outside class, using SCOPE RESOLUTION OPERATOR*/

    void disp();//should be declared inside class
};

void Device::disp(){ //METHODS define outside using SCOPE RESOLUTION OPERATOR
cout<<Device::id<<endl;//use scope resolution op to access var outside class
}

int main(){
Device d;
d.id=10;
d.disp();
    return 0;
}


54. Private Access Specifier _ C++ Object Oriented Programming :

#include<iostream>
using namespace std;

class ATM{
private:    //private access specifier
    int pin;    //private member variables cant be accessed outside the class

    void getpin(){  //private member functions cant be accessed outside
    cout<<pin-199<<endl;}

public:
    void setpin(int ipin){          /*private member var can be accessed 
thru’ a public member ftn of the same class*/
        pin=ipin;}

    void disp(){ 
        getpin();}
};

int main()
{
    ATM sbi;
    sbi.setpin(1234);
    sbi.disp();    //private data is hidden successfully
    return 0;
}

55. Class Constructors _ C++ Object Oriented Programming :

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

class Device{
private:
    string name;
    int id;
public: //constructor MUST be public..!!!!
/*Constructor syntax: className( ){ .... }
NOTE: strictly no return type,but it may take parameters*/
    Device(){  //constructor initializes properties
    name="noname";
    id=0;
    cout<<"constructor is called automatically, when object created"<<endl;
    }
};

int main()
{
    Device d;//object created, compiler calls CONSTRUCTOR automatically
    return 0;
}

NOTE: In our previous programs we didn’t mention constructor, but our program worked fine..its because compiler automatically constructs it, when object is created. If we need some statement executed inside it, then only we need to mention it manually,…but cant be called manually..!!!

i.e., In short, Constructor is a special function called automatically by compiler when we create object of class, it has same name of class, no return type, we cant call them manually,..constructors are normally used to initialise d properties of class and it should be public.

56. Overloading Class Constructors _ C++ Object Oriented Programming :

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

class Device{
private:
    string name;
    int id;
public:
    Device(){  //default constructor ( with no parameter)
    name="noname";
    id=0;
    cout<<"default constructor called"<<endl;}

    Device(string iname,int iid){  /*overloaded constructor (
 with iname and iid as parameters)*/
    name=iname;
    id=iid;
    cout<<"overloaded constructor called"<<endl;}

    void disp(){
    cout<<name<<"  "<<id<<endl;
    }
};

int main()
{
    Device d;//object created, default constructor called
    d.disp();

    Device e("NOKIA",1100);//object created, overloaded constructor called
    e.disp();
    return 0;
}

Note: if default constructor is not mentioned manually and only overloaded constructors with parameters are given manually, then compiler gives ERROR,since default constructor will not be added automatically, if we overload constructor.

57.a Default Class Constructor Parameters _ C++ OOPS :

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

class Device{
private:
    string name;
    int id;
public:
    Device(){
    name="noname";
    id=0;
    cout<<"default constructor called"<<endl;}

    Device(string iname,int iid=6600){//default parameter-6600,can be overwritten
    name=iname;
    id=iid;
    cout<<"overloaded constructor called"<<endl;}

    void disp(){
    cout<<name<<"  "<<id<<endl;
    }
};

int main()
{
    Device d;//default constructor called
    d.disp();

    Device e("NOKIA");//overloaded constructor calledwith one parameter
    e.disp();//one default parameter is taken

    Device f("NOKIA",1100);//overloaded constructor called with 2 parameters
    f.disp();//default parameter overwritten by passed value

    return 0;
}

NOTE: default parameter should be passed from right to left

57.b Default Class Constructor Parameters _ C++ OOPS :

Alternate way (for the previous concept)

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

class Device{
private:
    string name;
    int id;
public:
    Device(string iname="noname",int iid=0){    //default parameters passed
    cout<<"overloaded constructor called"<<endl;
    name=iname;
    id=iid;
    }

    void disp(){
    cout<<name<<"  "<<id<<endl;
    }
};

int main()
{
    Device f;     //overloaded constructor called with two default parameters
    f.disp();

    return 0;
}

NOTE: we can put only overloaded constructor and pass default parameters to it, and get our program work properly without error ..NO NEED OF DEFAULT CONSTRUCTOR

58. Destructors in a Class _ C++ Object Oriented Programming :

#include<iostream>
using namespace std;

class Device{
public:
    Device(){   //constructor
    cout<<"constructor called"<<endl;
    }
    ~Device(){    //Destructor
    cout<<"destructor called"<<endl;
    }
};

int main(){
    Device *d=new Device;    //constructor called

    delete d;    //destructor called
    return 0;
}

NOTE: Destructor is called when object goes out of scope or delete keyword is called for the object created by using new keyword. Destructor can’t take any parameter, as Constructors do. Destructor should be public and can be defined outside the class using scope resolution operator, same as Constructor.

59. C++ Destructors to Release Resources_Object Oriented Programming :

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

class Device{
private:
    string *name;
    int *id;
public:
    Device(string iname,int iid){
        name=new string;    //dynamic memory allocation
        id=new int;

        *name=iname;    //ATTENTION:*name,*Id since values NOT ADDRESS
        *id=iid;
    }
    ~Device(){
    delete name;      //deallocate memory
    delete id;
    cout<<"All memories are released"<<endl;}

    void disp(){
    cout<<*name<<"  "<<*id<<endl;}   /*ATTENTION:*name,*Id since we need values NOT ADDRESS*/
};


int main()
{
    Device *d=new Device("NOKIA",1100);   //dyn mem alloc, calls constructor
    d->disp();

    delete d;    //dealloc mem, calls destructor
    return 0;
}

60.a C++ Static Variables _ Static Members in Class _Object Oriented Programming :

#include<iostream>
using namespace std;

void disp();
int main()
{
    disp();
    disp();
    disp();
    disp();
    return 0;
}
void disp(){
    static int counter=0;    //only for the 1st time gets executed
    cout<<++counter<<" times called"<<endl; /*next time onwards the value in (DATA MEM)heap is acessed*/
}

60.b C++ Static Variables _ Static Members in Class _Object Oriented Programming :

Alternate way of using static variable(simpler version)

#include<iostream>
using namespace std;

void disp(){
    int a=10;
    static int b=5;
    a+=5;
    b+=10;
    cout<<a<<" "<<b<<endl;
}

int main()
{
    disp();  //15 15
    disp();  //15 25
    disp();  //15  35
    disp();  //15  45
    disp();  //15 55

    return 0;
}

static class member:

#include<iostream>
using namespace std;

/*static member var-has class scope,shared by all the objects of the class*/
class Device{
public:
    static int counter;     /*ATTENTION:should be initialized outside the class*/

    Device(){  //constructor
        counter++;      /*everytime obj is created, this will get incremented*/
    }

    void disp(){
    cout<<counter<<" devices found"<<endl;}
};

int Device::counter=0;    //initialize outside the class

int main()
{
    Device d;
    Device e;
    Device f;
    d.disp();   /*since same copy is shared by all objects,prints total count*/
    return 0;
}

61. C++ Static Methods in Classes _Object Oriented Programming :

#include<iostream>
using namespace std;

class Device{
public:
    static int counter;

    Device(){
        ++counter;
    }

    static void dispCount(){         //static method
       cout<<counter<<endl;      //static methods use only static varaibles
    }
};

int Device::counter=0;

int main()
{
    Device d;
    Device e;
    Device f;

    Device::dispCount();      /*use scope resolution operator to access static ftn*/
    return 0;
}

62. Friend Function _Object Oriented Programming :

#include<iostream>
using namespace std;

class Atm{
private:
    int pin;
public:
    Atm(int ipin){
    pin=ipin;}

    friend void dispPin(Atm obj);/*declare friend ftn, ATTENTION: object of the class should be passed as parameter!!!*/
    /*syntax: friend returntype ftnname(classname object)*/
};

void dispPin(Atm obj){ /*friend ftn can access all members of the class,including PRIVATE&PROTECTED members*/
cout<<obj.pin<<endl;}  /*access the member through d object- obj.pin*/

int main()
{
    Atm sbi(1234);
    dispPin(sbi);//obj of the class is passed as parameter
    return 0;
}

NOTE: friend function can access all members of a class, to which it is friend.

FRIEND CLASS can also be achieved by making a class friend to another class

syntax: friend class FrndClassName(MainClassName object)

63. Inheritance, Polymorphism _ Introduction :

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

class Base{
private:
/*!!!CANT be inherited*/

protected:
/*can be inherited*/

public:
/*can be inherited*/
    string name;
    void setname(string iname){
    name=iname;}
};

class Derived:public Base{ //inheritance
public:
    int id;
    void setid(int iid){
    id=iid;}

    void disp(){
    cout<<name<<" "<<id<<endl;} /* derived class inherited base class property name*/
};

int main()
{
    Derived d;//derived class object
    d.setname("rs");
    d.setid(123);
    d.disp();
    return 0;
}

NOTE: inheritance gives us code reusability, since baseclass member & mem.ftns are inherited by derived class. We need not to create those members again.

64. C++ Protected Access Modifier in Classes _Object Oriented Programming :

#include<iostream>
using namespace std;

class Base{
protected: /*same as private, BUT it can be inherited*/
    int id;
public:
    void setid(int iid){
        id=iid;}
};

class Derived:public Base{
public:
    void disp(){
        cout<<id<<endl;}
};

int main()
{
    Derived d;
    //d.id=786;  /*cant be accessed outside the class, since PROTECTED*/
    d.setid(123);
    d.disp();
    return 0;
}

NOTE: Protected can be inherited, available to same class and its derived class. BUT not outside the class.

65. C++ Access Control and Inheritance _ Object Oriented Programming :

Public access specifier: Makes the member available to same class in which its defined/declared + to its derived class and also outside the class.

Protected: Makes the member available to same class in which its defined/declared + to its derived class , BUT NOT outside the class.

Private: Makes the member available only to the same class in which its defined/declared, BUT NOT for derived class & outside the class.


PublicProtectedPrivate
Same class
Derived classX
Outside classXX
C++ Access Control and Inheritance

NOTE: Derived class can inherit all NON PRIVATE members, except Constructor, Destructor, Friend function and Overloaded operators.

This is the end of this level. In our next level we will dive deeper..Please do read the complete series of this blog to reach the Level from Novice to Expert.

If you find any error in SourceCode please let me know in the Comments. Corrections and Improvement Suggestions are highly appreciated. Thanks in advance..

love,

<R.S>

For Complete Sourcecode visit my Github Repo: Link provided in the final module

Rating: 4 out of 5.

RS-codes

2 thoughts on “CPP QuickReference – From Novice to Expert- Level3

Leave a comment

Design a site like this with WordPress.com
Get started