2

Main.cpp

#include <iostream>
#include "include/Numbers.h" 
#include <vector>
#include <string>
#include <fstream>


using namespace std;

int main()
{
    ofstream myofile;
    ifstream myifile;
    myofile.open("output.txt");
    myifile.open("input.txt");
    int number;
    Numbers input;

    if(myifile.is_open())
        while(myifile >> number) {
            input.push_back(number);
        }

    cout << input.size() << endl;


    myofile.close();
    myifile.close();

    cout << "Hello world!" << endl;
    return 0;
}

Numbers.h

#ifndef NUMBERS_H
#define NUMBERS_H
#include <vector>


class Numbers: public std::vector<int>
{
    public:
        Numbers();
        ~Numbers();
        int size();
        Numbers prob();

    protected:
    private:
};

#endif // NUMBERS_H

Numbers.cpp

#include "../include/Numbers.h"
#include <iostream>

using namespace std;

Numbers::Numbers()
{
}

Numbers::~Numbers()
{
    //dtor
}

I am trying to create a new Numbers class which inherits functions from vector class.

The error I am getting is undefined reference to 'Numbers::size()' although the push_back function didn't give any problem

I am using codeblocks to write my code, and I have included all files in the build properties

  • Add `int Numbers::size() {}` to Numbers.cpp – Borgleader Feb 05 '14 at 18:27
  • Yeah that worked. Thank you. But why didnt it give any problem with the push_back() function? – user3276516 Feb 05 '14 at 18:29
  • Because you inherited it from std::vector. You could also remove the size method entirely as it's define there. (I actually didn't notice you were inheriting from vector when I made my first comment). – Borgleader Feb 05 '14 at 18:30

1 Answers1

1

First, what you are doing there is not a good idea. It is generally not intended to use STL-classes as base-classes (except for those especially designed for this, such as std::unary_function). std::vector does not have any virtual methods, so it does not have any value as a public base-class. Making things worse, std::vector does not even have a virtual destructor, so when you use it polymorphically, you will probably create a memory leak:

void deleteVector(std::vector<int>* v)
{
    delete v;
}

deleteVector( new Numbers() );

In your case, you declared a Method Numbers::size which is not defined in the source-file. You could use a using declaration to use the size-method of your base-class, but that is not needed for public methods.

class Numbers: private std::vector<int>
{
public:
    using std::vector<int>::size;
};
Jens
  • 9,058
  • 2
  • 26
  • 43