[Solved] C++ inheritance question

I have a base class and a bunch of inherited classes.
I am doing something like this in the main.
baseclass* base[2];
base[0]= new _derived1("hello");
base[1]= new _derived2("world");
How do I code my base class or what-ever-else so that I CAN'T do this:
baseclass* base2;
base2 = new baseclass("class");
The base class has 1 constructor with an argument type string. I can't have a default constructor.
So in short. I can create a particular derived class, like a derived1, but can't create a plain base class. (it should throw a compilation error)
Any help would be appreciated.
Thanks.
Last edited by lamdacore (2011-02-06 00:38:43)

Oh I want a compile error when I do this:
baseclass* base2;
base2 = new baseclass("class");
Example code. So I don't want the base class to be able to make a Base type object. As soon as I do that it SHOULD throw a compilation error.
class Base{
public:
Base(string st):m_st(st)
virtual ~Base(){
virtual string ann() const{
return "";
virtual string bnn() const{
return m_st;
virtual string cnn(string msg) const{
string k="hey ";
k.append(msg);
return k;
private:
string m_st;
class derived1:public Base{
public:
derived1(string st):Base(st){
virtual ~derived1(){
cout<<"kill";
virtual string ann() const{
return "hullo";
virtual string bnn() const{
return Base::bnn();
virtual string cnn(string msg) const{
string k="hey ";
k.append(msg);
return k;
private:
string m_st;
Last edited by lamdacore (2011-02-06 23:38:23)

Similar Messages

  • Challenging question! (Does anyone how to solve this Javabat question?)

    Does anyone how to solve this Javabat question?
    Here is the link:
    http://www.javabat.com/prob?id=Array3.linearIn

    I'm a little surprised by the implied rating of this problem... it's a plain to-way merge. You can use the same template as for the merging step in merge sort:
    public boolean linearIn(int[] outer, int[] inner) {
      int i = 0;
      int j = 0;
      while (i < outer.length || j < inner.length) {
          if (j < inner.length && (i == outer.length || inner[j] < outer)) {
    // inner[j] smallest
    return false;
    else if (i < outer.length && (j == inner.length || outer[i] < inner[j])) {
    // outer[i] smallest
    i++;
    else {
    // inner[j] == outer[i]
    i++; j++;
    return true;

  • For loops & inheritance question

    I am trying this exercise dealing w/inheritance. I enter at command line a random number of c's, s's and m's. for checking,savings and money market. I then parse the string and check for the character. From there I create one of the accounts. then I am supposed to make a report that displays the past 3 months activities. the first account created gets 500 deposit the from there each account after the first gets an additional 400. so it would be: 500,900,1300,etc. Here is what I have so far, but the report part is where I can't figure out exactly how to go about solving it. Thanks in advance.
    public static void main( String args[] ){
         int intDeposit = 500;
         char charTest;
         Object [] objArray = new Object[args[0].length()];
         for ( int j = 0; j < 3; j ++ ){                        System.out.println( "Month " + ( j +1 ) + ":" );
             for( int i = 0; i < args[ 0 ].length(); i ++ ){
              charTest = args[ 0 ].charAt( i );
                         if (charTest == 'c' ){
                  BankAccount at = new  CheckingAccount( intDeposit );
                  objArray=at;
              else if( charTest == 's' ){
              BankAccount at = new SavingsAccount( intDeposit );
              objArray[i]=at;
              else if( charTest == 'm' ){
              BankAccount at = new MoneyMarket( intDeposit );
              objArray[i]=at;
              else{
              System.out.println( "invalid input" );
              }//else
              intDeposit += 400;
              System.out.println();
         }//for j
         for (int counter = 0; counter < objArray.length; counter ++ ){
              System.out.println( "Account Type: " +
                        objArray[counter].toString() );
              System.out.println( "Initial Balance: " +
                        (BankAccount) objArray[counter].getCurrentBalance() );
         System.out.println( "TotalDeposits: " + objArray[counter].getTotalDeposits() );
         System.out.println();
         }//for i
    }//main
    }//TestBankAccount.java\

    The only thing I think is wrong is the following line:
    System.out.println( "Initial Balance: " +                    (BankAccount) objArray[counter].getCurrentBalance() );
    Should be:
    System.out.println( "Initial Balance: " +                    ((BankAccount) objArray[counter]).getCurrentBalance() );

  • Constructor Inheritance Question

    Here's a quote from the Java Tutorials at http://java.sun.com/docs/books/tutorial/java/javaOO/objectcreation.html :
    "All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program."
    In order to fully understand this concept, I created two classes: a ClassParent and a ClassChild.
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
    public class ClassChild extends ClassParent
        public static void main(String[] args) {
            ClassChild child = new ClassChild();
    }Both classes compiled successfully, which raised the following question:
    I understand that the ClassParent default constructor calls the Object's no-argument constructor.
    Does the ClassChild also call the Object's constructor once it realizes that the ClassParent does not have a no-argument constructor?
    And a somewhat non-related question:
    Seeing how ClassParent calls Object's no-argument constructor if it does not have one of its own, does it also extend the Object class?
    Edit: After running the following code, I realized that the answer to my last question is yes:
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
           boolean test = tester instanceof Object;
           System.out.println(test);
    }Edited by: youmefriend722 on May 26, 2008 1:54 PM

    youmefriend722 wrote:
    I think I'm getting a basic grasp now but want to make sure that I'm not misunderstanding anything.
    Constructor inheritance:
    If a no-argument constructor is invoked but one isn't declared in that class, the superclass's no-argument constructor will be invoked. Well, sort of. If you invoke a constructor that doesn't exist, you get an error. Keep in mind that the invocation and the constructor may both be automatically supplied by the compiler, and that the compiler won't automatically create a no-arg constructor for a class if you define any constructors for that class.
    So if you don't define any constructors in a class, then a no-arg one is created automatically (at compile time) and (at runtime) when you instantiate that class, that no-arg constructor will try to invoke the superclass's no-arg constructor.
    But suppose you do define a constructor, one that takes an argument. Then if you try to invoke a no-arg constructor on that class, you'll get an error, and the superclass's no-arg constructor won't be invoked (because the error happens first).
    If the superclass does not have a constructor, then the superclass's superclass's constructor will be invoked.No. That never happens. Every class has a constructor (although it might have permissions which make it inaccessible, which is a whole other issue we'll worry about later).
    If the superclass does have a constructor but doesn't have a no-argument constructor, then there will be a compile-time error.Only if you try to invoke the no-arg constructor, which might happen implicitly. For example, if you write a superclass with a 2-arg constructor, and you write a subclass with a 1-arg constructor, and the 1-arg subclass's constructor invokes the superclass's 2-arg constructor, then there's no problem, even though in this example, the superclass doesn't have a no-arg constructor.
    Constructors in general:
    In every constructor, the superclass's no-argument constructor will be invoked if the none of the superclass's constructors are explicitly invoked.Yeah, I think that's right.

  • (SOLVED) Two KDE Questions

    1. How do you enable spell check in Kopete? It does not seem to want to check my spelling after I click the spell button or right click and select auto spell check. I checked my system and I do have aspell installed.
    2. How do I get a volume applet on the panel? I have used Kubuntu in the past and there was always a little speaker in the system tray section. This is not present with the current full KDE package which I have installed. How do I add it?
    Thank you so much for your help!
    Question 2 has been solved. Just start Kmix
    Last edited by czechman86 (2008-05-30 02:36:59)

    funkyou wrote:Do you have the appropriate language package for aspell installed? (example: aspell-de for german)
    i checked and i did not have the en package. thank you for that tip! the spelling in kopete will still not work however.

  • Multiple inheritance question

    This just occurred to me. I read the other day that all classes inherit Object. So if I have a class defined as public class A {
    }and I call toString() on an instance of this class, I get Objects toString implementation (assuming it has not been overridden). OK, this I understand.
    Now if instead I havepublic class A extends B {
    }and I call toString() on A, assuming it is not overridden in either A or B, I will still get Objects toString method. My question is, does A still extend Object, or does it inherit the fact that B extends Object? And what happens if I override toString() in B - what will I get if i call toString on an instance of A?

    java.lang.Object is at the root of all class inheritance hierarchies in Java. Therefore, all classes inherit from java.lang.Object, either directly or indirectly.
    When you call a method on an object of class Foo, Foo's inheritance hierarchy is traced starting with Foo and going all the way back to java.lang.Object, looking for an implementation of the method. The first implementation encountered is the one that gets used. So in your example calling toString on an instance of class A will result in B's toString method being executed.
    Hope this makes sense.

  • [Solved] Metacity theme question

    Hi,
    I use a modified version of the "Human" theme but it's not perfect yet.
    The ugly 'point' on the left should be removed and at this area the application icon should be shown.
    What is needed to modify? Thanks for help.
    Screenshot:
    metacity-theme.xml:
    http://pastebin.com/ZVx5My1U
    Edit: solved by myself
    Last edited by Radioactiveman (2011-03-21 17:56:57)

    anonymous_user wrote:
    Haptic wrote:What's wrong with asking 2 things in 1 thread?
    Arch Wiki wrote:Choose one topic per thread. Long threads are typically discouraged in the technical issue subforums. Try not to post multiple questions in a single topic -- this makes it difficult to search for specific problems.
    https://wiki.archlinux.org/index.php/Fo … ow_to_Post
    Sorry, I moved the other question to another topic.
    Nothing shows up in ncmpcpp
    mpd.conf
    http://paste.pocoo.org/show/342598/
    Last edited by Haptic (2011-02-22 02:49:02)

  • [solved] C++ - Inherited Classes

    #include <iostream>
    struct base
    void func1() { std::cout << "base::func1" << std::endl;
    void func2() { func1(); }
    struct inherited : public base
    void func1() { std::cout << "inherited::func1" << std::endl; }
    This is probably a pretty stupid question, but I have absolutely no clue how to do this.  I'm trying to get inherited::func2 to call inherited::func1 instead of base::func1 without defining inherited::func1.  This really is a conceptualised version of what I'm trying to accomplish, but it explains it well enough.
    I'm using the latest version of the GCC with the experimental C++0x support.
    Last edited by RetroX (2010-08-21 16:08:13)

    #include <iostream>
    struct base
      virtual void func1() { std::cout << "base::func1" << std::endl;
      void func2() { func1(); }
    struct inherited : public base
      virtual void func1() { std::cout << "inherited::func1" << std::endl; }
    Last edited by PirateJonno (2010-08-20 07:09:06)

  • Inheritance questions

    Say a superclass has 3 methods and 3 properties. NExt, I create a subclass which overrides these same 3 methods and properties. Either way, my question really is this... When casting up and down, when it is a subclass and a super class reference, are the properties preserved when it is cast(implicitly) up to a superclass reference, so that, in case it needs to be cast back down (explicitly) to its original subclass form, the subclass properties can still be referred to? Are the original variables still preserved (much like a static variable)?

    are the properties preserved when it is cast(implicitly) up to
    a superclass reference, so that, in case it needs to be cast backAn object instance does not change when it's casted into a superclass reference. This means it can be casted back (if this weren't the case, then all methods that return Object would be pretty useless).
    In addition, accessing an object method via a superclass reference does not mean that you'll invoke a superclass method. Instead, it invokes the method appropriate to the object (otherwise overriding and polymorphism would be pretty useless).
    However, accessing an object's instance variable via a superclass reference does access the superclass variable, not the subclass variable.
    I would suggest playing with this for a while ... here's something to start with:
    public class DROCPDP
        public static void main( String argv[] )
        throws Exception
            Base a = new Base();
            Sub b = new Sub();
            Base c = (Base)b;
            Sub d = (Sub)c;
            System.out.println("\nOperations on A:");
            System.out.println("a.var = " + a.var);
            a.method();
            System.out.println("\nOperations on B:");
            System.out.println("b.var = " + b.var);
            b.method();
            System.out.println("\nOperations on C:");
            System.out.println("c.var = " + c.var);
            c.method();
            System.out.println("\nOperations on D:");
            System.out.println("d.var = " + d.var);
            d.method();       
        private static class Base
            public String var = "Base";
            public void method()
                System.out.println("Called Base.method; variable = " + var);
        private static class Sub extends Base
            public String var = "Sub";
            public void method()
                System.out.println("Called Sub.method; variable = " + var);
    }

  • Small inheritance question

    Got a small quesiton about inheritance.
    I have a 'User' Class and extending that class is 'Player' and 'Enemy'.
    Player class and Enemy class contains extra stuff like different image and moves different.
    When I create a new player do I create an instance of the 'User' class or the 'Player' class?
    Also,
    If values change in the 'Player' class do the values also change in te 'User' class?
    I am fairly new to java.
    Thanks

    MarcLeslie120 wrote:
    Got a small quesiton about inheritance.
    I have a 'User' Class and extending that class is 'Player' and 'Enemy'.Sounds odd. Aren't some players also your enemy? Or is Player me, and everybody else is Enemy?
    Player class and Enemy class contains extra stuff like different image and moves different.Okay. If it's just different, that's one thing. If it's adding extra methods, you probably don't want to inherit.
    When I create a new player do I create an instance of the 'User' class or the 'Player' class?If it's going to be a Player, you need to create a Player.
    If values change in the 'Player' class do the values also change in te 'User' class?If you mean an instance variable (a non-static member variable), then there aren't two separate objects. There's just one object, that is both a Player and a User. The variable exists only once.
    Your inheritance hierarchy smells funny, but without more details about what these classes represent and what you're trying to accomplish, it's hard to provide concrete advice.

  • [SOLVED]Noob source question

    I was curious because every single video I've seen(I use video's to learn) on installing Arch is only about installing ArchBang, and when going through the install process they only seem to have to go through setting the clock, partitioning the harddrive, configuring the system and installing bootloader. So I was wondering if choosing the source is necessary if I am installing from USB?
    Last edited by xworld (2012-07-22 02:18:34)

    Have you read The Arch Linux Beginner's Guide? It is not recommended to install Arch by following any other method. Furthermore, if you're really installing ArchBang, rather than Arch Linux, you should ask about it on their fine forums - I'm not saying that's what you're doing, I'm just pre-empting the possibility, since you haven't said what iso you're using.
    To answer your question about sources, is there any reason you can't first make a guess and then redo the install if things go wrong? You shouldn't use Arch Linux if you're not willing to experiment and hack.

  • [SOLVED] An offlineimap question

    Greetings,
    I am trying to set up offlineimap with a Gmail account. Due to a network issue during the initial sync, I was only able to download ~50% of the mail stored with Google (I had to SIGINT, since offlineimap didn't seem to recognize that the had connection restored). My question is: if I were to evoke "offlineimap -o" again, how would the sync occur? Would I be pushing the incomplete local repo to Gmail (and hence deleting half the mail in the account), or would the local repo continue to be grown by downloading the to-be-copied mail presently on the Google server?
    Thanks! And, yes, I did try reading the f manual; I can't work out how to read the local cache files (~/.offlineimap/...) though.
    Last edited by tomgg (2013-09-08 10:40:26)

    I'm sure you wouldn't have given any wrong info (you appear to be a well privileged poster) but I will wait until I can confirm this myself (don't want to lose all my email!). Can you explain the local cache files for me? The files I can find look like
    n-1:S
    n:
    n+1:S
    for some integer n; so, the integer is obviously some number Google uses to index the mail, but what is the "S" or its possible variants?

  • [solved] Gnome lockscreen questions

    1. Is there a way to get rid of the necessity to pull up the gnome lockscreen or press enter or escape before I can type the password? I want to type directly the password without pressing any button before.
    2. Can I set up gnome to blank the screen when I press CTRL+ALT+L instead of showing bhe tackground and the time?
    Thx
    Edit: The bug is solved in Gnome 3.8. Thanks
    Last edited by tuxero (2013-04-11 13:18:59)

    I think this is not possible, but I can suggest you a workaround. I use the i3 window manager, and it comes with a utility to lock the screen which does exactly what you want. I think the lock utility can work even if you are not using i3wm. Try installing i3lock with pacman, and then in Gnome define a keyboard shortcut for
    i3lock -d -c 000000
    It does exactly what you want. It blanks the screen with dpms off(or standby) and locks it. to unlock just start typing your password(the screen will turn on with a black backgroud(you can change the color after -c if you like, it is in hex)) and press enter.
    Last edited by plam (2013-03-24 15:50:06)

  • [SOLVED]2 DWM questions

    exactly what the topic says
    1. How much RAM does dwm take up? maybe someone could take a screenshot with archey while idling with nothing else running?
    2. How much C experience does it take to configure dwm? Iv looked at some sample configs and it doesnt look incredibly complex
    Iv looked for the answer to those 2 questions but could not find them so are there any dwm users that could quickly answer them?
    Last edited by markbabc (2010-11-29 16:10:00)

    2. Patches will work correctly if you do like what wiki said . But multiple patches can cause problem like bharani said. And c prog is easy to read, no master needed to read and customize config.h file . And there's #archlinux channel + bbs forum for you to ask

  • [Solved] Quick ln Questions...

    How can I symlink my /tmp with /dev/shm? Would it just be:
    ln -s /dev/shm /tmp
    Last edited by haxit (2009-03-22 02:31:56)

    Please edit your first post to indicate the thread is [SOLVED] (if it is)
    Last edited by Ranguvar (2009-03-22 02:06:30)

Maybe you are looking for

  • Logic for Open Sales order qty

    What should be the logic given to determine "open sales order qty" during designing a report. Note the criterias are as under: 1) Open sales order qty is the confirmed qty less the delivery qty. 2) The delivery qty should be delivery order qty (The d

  • Output type for POs

    Hi, We have condition record for 2 output types, But I need only one output type to be populated in PO output. with out deleting the other one in condition record. Is there any way to do it. Regards Arun

  • No planning files for backflush components- MRP V1

    experts, no planning file is generated for the compoent with MRP type V1- material backflush with 261 mvmt. pls advice! here then to incluse this component to generate planning file what necessary setting needs to be done?

  • IMessage - email verification failed

    After changing my password, my iMessage is unable to verify my email address. It says an email with a verification link has been sent to my email but I got no emails so far. I've tried about five times. Can anybody help?

  • Help, PE7 will not install

    Help - anyone that may have seen this...please On attempting to install PE7 from a legal purchased CDROM. After choosing language and clicking OK to start install, I get a dialog that give this insane statement... Either Adobe Premiere Elements 7.0 i