Thread: General Class

  1. #1
    Registered User
    Join Date
    Jun 2005
    Posts
    1

    General Class

    have to declare a variable(class) depending on some info I get from a file, something like this:
    Code:
    /*************************/
    (...)
    if (what_I_read == '1')
    Class1 system();
    else
    Class2 system();
    (...)
    
    system.start();
    system.stop();
    /**************************/
    So I want the variable 'system' to be something different depending on certain conditions, but I get a compiling error because 'system' isn't declared. How can I do something like that? Maybe another Template Class???

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    You're pretty much looking at polymorphism with this problem:
    Code:
    // Oversimplified example
    class Base {};
    class Derived1: public Base {};
    class Derived2: public Base {};
    
    Base *system;
    
    if (something)
      system = new Derived1();
    else
      system = new Derived2();
    
    system->start();
    system->stop();
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    May 2005
    Location
    Sweden
    Posts
    16
    Also, just so you know, the following code piece does not create an instance of class SomeClass, it declares a function returning an instance of class SomeClass:
    Code:
    SomeClass a();
    a.method();  // This is wrong, 'a' is a function not an instance of SomeClass
    This is the correct way to create an instance of a class with the default constructor
    Code:
    SomeClass b;
    b.method();  // This works, because now 'b' is indeed an instance of SomeClass
    Just thought you'd like to know that, seeing as how you are declaring functions in your own example...

  4. #4
    Registered User
    Join Date
    Jun 2004
    Posts
    722
    and
    Code:
    delete system;
    'system' isn't declared.
    you system var is declared in 2 diferent scopes, which are the if-block and else-block.
    outside them, system doesn't exist. you have to declare it outside the ' if - else ' like Prelude showed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Specializing class
    By Elysia in forum C++ Programming
    Replies: 6
    Last Post: 09-28-2008, 04:30 AM
  2. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Mmk, I give up, lets try your way. (Resource Management)
    By Shamino in forum Game Programming
    Replies: 31
    Last Post: 01-18-2006, 09:54 AM