Thread: Derived classes and initialization lists

  1. #1
    Anal comment spacer DominicTrix's Avatar
    Join Date
    Apr 2002
    Posts
    120

    Derived classes and initialization lists

    Hi, I have a base class something like:

    Code:
    class MyClass
    {
       protected:
          const int nRecords;
          int *records;
       
       public:
          ...
    };
    And I would like my derived classes to initialize the 'const int nRecords' value in their constructor, i.e.

    Code:
    class MyDerivedClass : public MyClass
    {
       public:
          MyDerivedClass() : nRecords(10) {}
    
       ...
    }
    When I try to compile such code however, I get the follwing error (using DevC++ v4.x):

    "Class 'MyDerivedClass' does not have any field named 'nRecords'"
    Any suggestions as to how I could work around this?

    dt
    Last edited by DominicTrix; 09-05-2004 at 05:07 PM. Reason: error in code
    "The most important thing about acting is honesty. If you can fake that you've got it made" - George Burns

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Any suggestions as to how I could work around this?
    Don't try to, it's a good thing. Your classes should generally not share members except through a well defined interface:
    Code:
    #include <iostream>
    
    class A {
      int i;
    public:
      A(int init)
        : i(init)
      {}
    protected:
      int get()
      {
        return i;
      }
    };
    
    class B: public A {
      int j;
    public:
      B()
        : A(10), j(20)
      {}
    
      void print()
      {
        std::cout<< get() <<" -- "<< j <<std::endl;
      }
    };
    
    int main()
    {
      B b;
    
      b.print();
    }
    My best code is written with the delete key.

  3. #3
    Anal comment spacer DominicTrix's Avatar
    Join Date
    Apr 2002
    Posts
    120
    Ah, I see. So I can call the base class' constructor in the derived class' init list and pass that a value to initialise my constant?

    Nice one, thanks.
    "The most important thing about acting is honesty. If you can fake that you've got it made" - George Burns

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. const in classes
    By Sharke in forum C++ Programming
    Replies: 3
    Last Post: 05-07-2009, 11:25 AM
  2. Bool initialization in class
    By FlyingIsFun1217 in forum C++ Programming
    Replies: 10
    Last Post: 08-05-2008, 02:33 AM
  3. Can you Initialize all classes once with New?
    By peacerosetx in forum C++ Programming
    Replies: 12
    Last Post: 07-02-2008, 10:47 AM
  4. Classes that can crash during initialization
    By drrngrvy in forum C++ Programming
    Replies: 23
    Last Post: 06-27-2006, 06:13 PM
  5. Questions on Classes
    By Weng in forum C++ Programming
    Replies: 2
    Last Post: 11-18-2003, 06:49 AM