vectors and inheritance in C++

Jun 14, 2009 at 11:35pm
Hi,
I was trying to use inheritance to make the existing std::vector to a two dimensional vector.Here is the code below.
#include "stdafx.h"
#include<vector>
#include<iostream>
using namespace std;
//TwoDVector.h
class TwoDVector:public vector<char>
{
public:
TwoDVector(int x,int y);
const int xDimension;
const int yDimension;
vector<char> TwoD;
char get(int x,int y);
void put(int x,int y,char c);
};
//TwoDVector.cpp
#include "stdafx.h"
#include<vector>
#include "TwoDVector.h"
#include<iostream>
using namespace std;

//TwoDVector class

TwoDVector::TwoDVector(int x,int y): xDimension(x),yDimension(y),twoD(xDimension*yDimension)
{
for(int i= 0;i<xDimension*yDimension;i++)
{
twoD[i] = ' ';
}

}
char TwoDVector::get(int row,int col)
{
return(twoD[row*xDimension+col]);
}

void TwoDVector::put(int row,int col,char value)
{
twoD[row*xDimension + col] = value;
}

But I am getting the following errors.Please Could someone help?
1>Compiling...
1>TwoDVector.cpp
1>.\TwoDVector.cpp(10) : error C2614: 'TwoDVector' : illegal member initialization: 'twoD' is not a base or member
1>.\TwoDVector.cpp(13) : error C2065: 'twoD' : undeclared identifier
1>.\TwoDVector.cpp(19) : error C2065: 'twoD' : undeclared identifier
1>.\TwoDVector.cpp(24) : error C2065: 'twoD' : undeclared identifier
Jun 14, 2009 at 11:46pm
Since none of vector's members are virutal (not even its destructor), you're better off not derviing from vector. You could probably hack together something that works, but it would be a lot of effort and would undoubtedly behave strangely if used a certain way (I've tried deriving from STL classes before -- it's not fun or easy).

Instead, you can make your own class which 'has-a' vector, and simply interfaces outside of it.

1
2
3
4
5
6
7
8
class vector2d
{
public:
  // get/set stuff here

protected:
  vector<int>  thevectortouse;
};


Of course instead of using int like I do here (and like you did in your example), you could make this a template class:

1
2
3
4
5
6
template <typename T>
class vector2d
{
  //...
  vector<T>  thevectortouse;
};
Jun 14, 2009 at 11:49pm
What makes you think std::vector can or should be subclassed? (Hint: Containers are not designed to be subclassed. You can tell by the lack of a virtual destructor.)

typedef std::vector<std::vector> 2dVector;

And then create a factory function to make constructing them easier.
Jun 14, 2009 at 11:56pm
To Disch
Thanks for the reply.
Even though I removed the :vector from the two dimensional vector still I am getting the same errors.Could you help?
Jun 15, 2009 at 12:01am
sorry! It was a typo.
Topic archived. No new replies allowed.