Simple Query!!

Hi Friends,

I came across one of the code snippets on some web portal.I am not sure if something like assigning an address of derived class object to a base class pointer is required when no virtual mechanism is involved.Can some one highlight on this if I am missing on any usage of such pointers.

Code snippet as belows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;
class BaseClass {
  int i;
public:
  void setInt(int num) { 
    i = num; 
  }
  int getInt() { 
    return i; 
  }
};
class derived: public BaseClass {
  int j;
public:
  void setJ(int num) { 
     j = num; 
  }
  int getJ() { 
     return j; 
  }
};
int main()
{
  BaseClass *baseClassPointer;
  derived d;
  baseClassPointer = &d;     // BaseClass pointer points to derived object
                             // access derived object using BaseClass pointer
  baseClassPointer->setInt(10);
  cout << baseClassPointer->getInt() << " ";

  return 0;
}
Looks pointless to me

The functions getJ and setJ cannot be accessed via the base class pointer

with no virtual mechanism you basically have the equivalent of a base class object only via the pointer
Topic archived. No new replies allowed.