Fingolfin
Fingolfin

Reputation: 27

c++ How to get acces of function that is in parent class?

I have class Books and child class BookClient.

In class Books their is function that calculates age of book:

int age()
{return 2017 - getage();}

I want function that prints books that are >5 age and are form certain publisher.

I am using range-based for loop to access the vec.

vector <BookClient> vec;

void printageover5(string publisher)
{
    for (const auto& cs : vec)
    if (cs.age() > 5 && getpublisher()==publisher)
    {
        ..........
    }
}

int main()
{
printageover("Amazon");
}

getpublisher() is member of class Book Client

And their is the error:

the object has type qualifiers that are not compatible with the member function
 object type is: const  Books 

Upvotes: 1

Views: 68

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

The problem is that age is not a const member function, so you cannot call it on a const reference.

Change the declaration to

int age() const { return 2017 - getage(); }

and make sure that getage() member function is also declared const.

int getage() const { ... }

Note: If you would like your code to be correct for longer than one year, hard-coding the current year is not a good idea.

Upvotes: 3

Related Questions