Thread: const parameter question

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663

    const parameter question

    I get the following error(marked in the code):
    error C2662: 'species' : cannot convert 'this' pointer from 'const class Duck' to 'class Duck &'
    Conversion loses qualifiers

    Code:
    #include<iostream>
    using namespace std;
    
    class Duck
    {
    public:
    	virtual void species() = 0;
    };
    
    class Mallard : public Duck
    {
    public:
    	void species()
    	{
    		cout<<"Mallard"<<endl;
    	}
    };
    
    
    void operateDuck(const Duck* pDuck)
    {
    	pDuck->species();
    }
    	
    int main()
    {
    	Mallard myDuck;
    	operateDuck(&myDuck);
    	
    	cout<<endl;
    	return 0;
    }

  2. #2
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    You need to tell the compiler that the species function doesn't alter the object:
    Code:
    class Duck
    {
    public:
    	virtual void species() const = 0;
    };
    
    class Mallard : public Duck
    {
    public:
    	void species() const
    	{
    		cout<<"Mallard"<<endl;
    	}
    };
    C++ FAQ Lite: What is a "const member function"?

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Ah hah. Const objects can only call const member functions(they have to be assured they will not be changed inside the function). Since I declared the parameter const, then inside the function it is a const object and species() is not a const member function. Adding const to the species() function in the Mallard class just causes more errors because the abstract base class version was not declared as const. So, you have to declare the base class version const.

  4. #4
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    lol. I guess I was writing my post when you posted. Thanks.

  5. #5
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    7stud is so good at programming, he even answers his own questions. Booyah!
    Sent from my iPadŽ

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Need help implementing a class
    By jk1998 in forum C++ Programming
    Replies: 8
    Last Post: 04-05-2007, 03:13 PM
  3. "error: incomplete type is not allowed"
    By Fahrenheit in forum C++ Programming
    Replies: 9
    Last Post: 05-10-2005, 09:52 PM
  4. Certain functions
    By Lurker in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2003, 01:26 AM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM