Thread: derived class question

  1. #1
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853

    derived class question

    Sorry for opening so many new threads. I ll try not to pollute the forum for the next few days with my questions

    I want to do this:
    Code:
    class A
    {
        string name;
        void display(){cout << name};
    };
    
    class B : public A
    {
        void display(){cout << name << "B"};
    };
    
    list<A> list;
    put objects of A and B class in list
    for (everything in the list) p->display();
    This will use always the A::display. I want if the object is B to use the B::display. I understand that this in not possible the way I do it.

    What would be the best way to do so?
    I thought of adding a flag in the A class, which is set on upon constructing a B class to 1, so that way I can do this:
    Code:
    for (everything in the list) if (flag) (*(B*)p).display() else p->display();
    Which should work. But then again I don't think this is possible if p is an iterator, eh?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    display() should be declared virtual in A, and then list should contain (smart) pointers to A, since polymorphism works via pointers and references.

    Once that is done, you can just call p->display() and the correct function will be called depending on the type of the object pointed to by p.

    Oh, and A's destructor should be declared virtual as well.
    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
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    First, you need to make display() a virtual function.
    Second, you can't store a B in a list<A>. You need to use pointers if you want to do that, such as list<A*>
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  4. #4
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    There are no such things as stupid questions. Just smart assed answers. In my opinion this is a very good question that a lot of new programmers may find themselves asking.

  5. #5
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853

    Unhappy

    Thanks. I think no-pointer Java is still stuck in my brain. Now I am tempted to ask: how would you do this in Java?

    So I have another question.
    Code:
    #include <iostream>
    #include <string>
    #include <vector>
    #include <list>
    using namespace std;
    
    class Item
    {
    public:
    	string name;
    	virtual void display(void)	{
    		cout <<  name;
    	}
    	Item(){};
    	Item(string str) {name = str;}
    };
    
    
    class Weapon : public Item
    {
    public:
    	Weapon(){};
    	void display(void){
    		cout << name << "+" << enchantment;
    	}
    };
    
    class Character 
    {
    public:
    	list<Item*> items;;
    	
    	void addItem(Item* item) {
    		items.push_back(item);
    		items.sort(Item::itemCmp);
    	}
    	void displayItems() {
    		list<Item*>::iterator it;
    		int pos=0;
    		for(it = items.begin(); it!=items.end(); ++it) {
    			cout << ++pos << ". "; (*it)->display(); cout << endl;
    		}
    	}
    	Character(){};
    };
    
    int main()
    {
            Character c;
    	Item i("apple");
    	Weapon w;
    	w.name = "sword";
    	w.enchantment = 1;	
    	c.addItem(&i);
    	c.addItem(&w);
    	c.displayItems();
    }
    This is some of my code. The question is if I change the addItem function like this:
    Code:
    	void addItem(Item item) {
    		items.push_back(&item);
    		//items.sort(Item::itemCmp);
    	}
    and do this:
    Code:
    ...
    	c.addItem(i);
    	c.addItem(w);
    	c.displayItems();
    then it doesn't work. It prints this:
    1. sword+1
    2. sword+1

    instead of
    1. apple
    2. sword+1

    in general it prints the last item only, like all the pointers in the list are pointing to the same last added item. Why?

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Code:
    	void addItem(Item item) {
    		items.push_back(&item);
    		//items.sort(Item::itemCmp);
    	}
    The first thing this function does is make a copy of the Item that you give it, and give that copy the local name "item". You then add the address of this local item to your items list. When the function ends, the local copy goes away, leaving your list pointing to ... nothing in particular.

    In your case, since nothing happened between the two calls, you got the same local address each time.

  7. #7
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Quote Originally Posted by C_ntua View Post
    Thanks. I think no-pointer Java is still stuck in my brain.
    Java does have pointers; they just call them references for some reason.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I would be very careful with your implementation here...
    You're storing pointers to local variables. They could go out of scope.
    My suggestion is: either you store copies of the objects or
    you allocate the objects you add on the heap and use smart pointers when storing them.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 01-13-2008, 05:57 PM
  2. Two conceptual questions
    By AntiScience in forum C++ Programming
    Replies: 3
    Last Post: 11-01-2007, 11:36 AM
  3. My Window Class
    By Epo in forum Game Programming
    Replies: 2
    Last Post: 07-10-2005, 02:33 PM
  4. Replies: 4
    Last Post: 12-29-2002, 12:29 AM
  5. base and derived class
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 12-12-2001, 03:11 PM