Answer to Question #261728 in C++ for Rohit Swain

Question #261728

1) Write a C++ programme which demonstrate static binding and dynamic binding.

2) Write a C++ programme which demonstrate vitual destructor.


1
Expert's answer
2021-11-06T13:51:57-0400

1)

#include <iostream>
#include <string>
using namespace std;
class Person{
    protected:
    string name;
    int age;
    public:
    Person(string n, int a): name(n), age(a){}
    virtual void print(){}
};
class Student: public Person{
    protected:
    int std_id;
    float cgpa;
    public:
    Student(string n, int a, int id): 
        Person(n, a), std_id(id){}
    void setCGPA(float gpa){
        cgpa = gpa;
    }
    void print(){
        cout<<"Name: "<<name<<endl;
        cout<<"Age: "<<age<<endl;
        cout<<"Student ID: "<<std_id<<endl;
        cout<<"CGPA: "<<cgpa<<endl;
    }
};
int main(){
    Person *ptr;
    Student Lucius("Lucius", 22, 11620641);
    ptr = &Lucius;
    //setCGPA is statically bounded
    Lucius.setCGPA(4.9);
    
    //print() is dynamically bounded
    ptr->print();


    return 0;
}

2)

#include <iostream>
#include <string>
using namespace std;
class Person{
    protected:
    string name;
    int age;
    public:
    Person(string n, int a): name(n), age(a){
        cout<<"Created a new person...\n";
    }
    virtual ~Person(){
        cout<<"Destroyed a person...\n";
    }
};
class Student: public Person{
    protected:
    int std_id;
    float cgpa;
    public:
    Student(string n, int a, int id): 
        Person(n, a), std_id(id){
            cout<<"Created a new student...\n";
        }
    void setCGPA(float gpa){
        cgpa = gpa;
    }
    ~Student(){
        cout<<"Destroyed a student...\n";
    }
};
int main(){
    Person *ptr = new Student("Lucius", 22, 382323);
    delete ptr;
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS