Blog Archives

Inheriting values from an object of a base class easily using pointers

I am really happy and proud to post this code here.. This code was an intelligent work by Devika, my friend. Really appreciate her thinking and creativity.. :D. Good work!!

This is an easier way to solve the problem i discussed in previous post : Inheriting values from an object of a base class.

#include <iostream.h>
#include <string.h>
#include <conio.h>
class student
{
protected:
  int roll;
  char name[20];
  int m1,m2;
public:
  void input(int r, char nm[20], int mrk1, int mrk2)
  {
    roll = r;
    strcpy (name,nm);
    m1 = mrk1;
    m2 = mrk2;
  }

};
class result : public student
{
  int total;
public:
  void print()
  {
    total = m1 + m2;
    cout << "Roll No : " << roll<< endl
    << "Name : "<<name << "Total : " << total << endl << endl;
  }
};
void main()
{
  clrscr();
  result r1,r2;
  student *s1 = &r1;
  student *s2 = &r2;
  s1->input(10, " name 1 ", 20,20);
  s2->input(15, " name 2 ", 10,10);
  r1.print();
  r2.print();
  getch();
}

Inheriting values from an object of a base class

Little geeky ;)! I had a thought of inheriting values from the object of base class, to the object in derived class.

The question is: create a class student with data members rollno, name, mark1, mark2. Now define a class result derived from ‘student’ with a data member result. now we are accepting the details in class ‘student‘ and then we are going to find the result/ total in class ‘result‘. For that the values of object of ‘student’ has to be copied to ‘result’..

#include <iostream>
#include <string.h>
using namespace std;
class student
{
protected:
  int roll_num;
  char name[20];
  float m1, m2;
public:
  void input(int r, char nm[20], float mrk1, float mrk2)
  {
    roll_num = r;
    strcpy (name, nm);
    m1 = mrk1;
    m2 = mrk2;
  }
  friend class result;
};
class result: public student
{
  float total;
public:
  result(student s)
  {
    roll_num = s.roll_num;
    strcpy (name, s.name);
    m1 = s.m1;
    m2 = s.m2;
    total = m1 + m2;
  }
  void print()
  {
    cout << "Roll No : " << roll_num << endl
         << "Name : " << name << endl
         << "Marks : " << m1 << "\t" << m2 << endl
         << "Total : " << total << endl << endl;
  }
};

int main()
{
  student s1;
  s1.input(10,"Name1",20,20);
  result r1(s1);
  r1.print();
  student s2;
  s2.input(15,"Name 2",10,10);
  result r2(s2);
  r2.print();
  return 0;
}

Got a better way to this? Just let us know.. 😀