CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Threaded View

  1. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: How to Call base Class Constructor

    Originally posted by Exceter
    class X {
    public:
    X();
    X(int);
    } ;
    class Y : public X {
    public:
    Y();
    f() {//call X()};
    G() {//call X(int)};
    };
    There is a reason why those functions are called constructors. What you are asking is impossible. How can you call the constructor if the derived class has already been constructed? Constructors are only called when constructing objects.

    If you want to call a function in class X, make it a regular (non-constructor) function and call it from your Y class.
    Code:
    class X {
    public:
        X() { DoXFunc(); }
        X(int n) { DoX2Func(n); }
    
    protected:
        void DoXFunc() { }
        void DoX2Func(int n) { }
    };
    
    class Y : public X {
    public:
       Y();
        void f() { DoXFunc(); }
        void G() { DoX2Func(1); }
    };
    And if from the Y constructor, you wanted to call a certain X constructor, you use something called a member-initialization list. But the bottom line is that you don't call constructors explictly, constructors are called automatically whenever you create an object.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; May 29th, 2003 at 11:48 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured