How can I make the base class unable to instantiate?

This is a discussion on How can I make the base class unable to instantiate? within the C++ Programming forums, part of the General Programming Boards category; For instance, classes A, B, and C derive from base class X. How can I make sure it's only A, ...

  1. #1
    Software engineer
    Join Date
    Aug 2005
    Location
    Oregon
    Posts
    283

    How can I make the base class unable to instantiate?

    For instance, classes A, B, and C derive from base class X. How can I make sure it's only A, B, and C that can instantiate, and not X? Thanks in advanced.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,993
    Provide X with a pure virtual function, e.g. virtual ~X() = 0;
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    pure virtual methods:
    Code:
    class X
    {
      X();
      ~X();
    
      virtual void PureVirtualMethod() = 0;
    };
    Of course it must be implemented in a subclass.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,454
    Making all constructors of X or its destructor protected also effectively prevents instantiation (except within X's member functions or its friends). That ability to instantiate only in defined places can be useful at times.

  5. #5
    Software engineer
    Join Date
    Aug 2005
    Location
    Oregon
    Posts
    283
    That should do the trick. Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. call base class function or derived class function
    By George2 in forum C++ Programming
    Replies: 4
    Last Post: 03-18-2008, 05:23 AM
  2. Creating a database
    By Shamino in forum Game Programming
    Replies: 19
    Last Post: 06-10-2007, 01:09 PM
  3. Problems w.r.t Virtual Base Class (inheritance)
    By pankajdynamic in forum C++ Programming
    Replies: 1
    Last Post: 04-15-2002, 10:28 AM
  4. Difficulty superclassing EDIT window class
    By cDir in forum Windows Programming
    Replies: 7
    Last Post: 02-21-2002, 04:06 PM
  5. base and derived class
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 12-12-2001, 02:11 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21