Advertisement

Nested Constructors

Started by May 08, 2001 06:12 AM
2 comments, last by gimp 23 years, 9 months ago
This is probably simple but... Class A : public B When creating a class A B''s constructor didn''t get called (I think). Is there something I need to do to make sure it gets kicked off? Many thanks Chris
Chris Brodie
B's constructor will always be called, before executing the body of A's constructor.

A simple program to show the constructor sequence is the following:

      #include <iostream>using namespace std;class B{public:  B() { cout << "B::B()" << endl; }  virtual ~B() { cout << "B::~B()" << endl; }};class A : public B{public:  A() { cout << "A::A()" << endl; }  ~A() { cout << "A::~A()" << endl; }};intmain(){  A a;  return 0;}  


When compiled and executed, this will give the following output:

B::B()
A::A()
A::~A()
B::~B()

HTH

Edited by - JungleJim on May 8, 2001 8:01:15 AM

Edited by - JungleJim on May 8, 2001 8:02:03 AM
Advertisement
If you have a constructor that needs parameters, you call it like so;
  class B{public:   B(int i)   {   };};class A : public B{   A(int i)   : B(i)   {   };};  

Just the same as parameter initialisation.
class _2dpoint
{
public:
int x, y;
_2dpoint(int nx, int ny)
{
x = nx;
y = ny;
}
};

class _3dpoint : public _2dpoint
{
public:
int z;
_3dpoint(int nx, int ny, int nz) : _2dpoint(nx, ny)
{
z = nz;
}
};

hope you get the point

Arkon
[QSoft Systems]

This topic is closed to new replies.

Advertisement