Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a field of an abstract class as a default argument of a method (c++)

I wrote an abstract class called "List", which I basically use as an interface for other implementation methods of lists (such as dynamic array and linked list).

Now, I have a method called "add", with 2 arguments, the first one is the data to add and the second is the position where to add. I want to set the default value of this position to be the end of the list (i.e, its size).

Here’s what I wrote:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#ifndef LIST_H
#define LIST_H

template <class T>
class List
{
    public:
        List(): m_size(0) {}
        virtual bool isEmpty() const=0;
        virtual void set(int index, T value)=0;
        virtual int getSize() const=0;
        virtual void add(T data, int index = m_size )=0;        //The problem is here    
        virtual T remove(int index)=0;
        virtual ~List(){}
        virtual T operator[](int index) const =0;
        virtual bool operator==(const List<T>& other) const =0;

    protected:

        int m_size;

};
#endif // LIST_H

But I get the following error:

error: invalid use of non-static data member 'List<T>::m_size'|

Is there a way to fix this problem?

Also, is it correct to implement the constructor as I did? do I need to call this constructor in the init line of the derived classes constructors or does the compiler does it implicitly?

Thanks in advance.

>Solution :

You cannot use members as default arguments of methods. Instead write an overload (it doesnt need to be virtual when it calls the virtual add(T,int):

void add(T data) {
     add(data,m_size );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading