Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

Abstract class and friend function

Virtual functions

class Base {
public:
    virtual void print()
    {
        cout << "Base Function" << endl;
    }
};
class Derived : public Base {
public:
    void print()
    {
        cout << "Derived Function" << endl;
    }
};
int main()
{
    Derived derived1;
    // pointer of Base type that points to derived1
    Base* base1 = &derived1;
    // calls member function of Derived class
    base1->print();
    return 0;
}
// Output :
// Derived Function

Pure virtual functions

class A {
public:
    virtual void s() = 0;
    // Pure Virtual Function
};

Abstract class

Properties of the abstract classes:

class Base {
public:
    virtual void s() = 0; // Pure Virtual Function
};

class Derived : public Base {
public:
    void s(){
        cout << "Virtual Function in Derived_class";
    }
};

int main()
{
    Base* b;
    Derived d_obj;
    b = &d_obj;
    b->s();
}
// Output
// Virtual Function in Derived_class

Friend function

class class_name {
    friend data_type function_name(argument);
    // syntax of friend function.
};

class Rectangle {
private:
    int length;

public:
    Rectangle() {
        length = 10;
    }
    friend int printLength(Rectangle); // friend function
};

int printLength(Rectangle b)
{
    b.length += 10;
    return b.length;
}

int main()
{
    Rectangle b;
    cout << "Length of Rectangle: " << printLength(b) << endl;
    return 0;
}
// Output :
// Length of Rectangle : 20

Characteristics of friend function:

Interview Questions

Resources