Thread: How can I make the base class unable to instantiate?

  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
    28,413
    Provide X with a pure virtual function, e.g. virtual ~X() = 0;
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    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,815
    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, 05:06 PM
  5. base and derived class
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 12-12-2001, 03:11 PM