constructor problem
Nov 18, 2012 at 11:12pm UTC
This is probably a dumb mistake but I am making a vector class to take negative indices. I am having a problem when implementing the constructors. Here is my header
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#ifndef _LBVECTOR_H
#define _LBVECTOR_H
#include <cstdlib>
#include <cassert>
#include <iostream>
template <class Item> class lbvector
{
public :
// default constructor 0 elements
// postcondition: vector of zero items constructed
lbvector( )
{
myCapacity = 0;
myList = 0;
myUpper = 0;
myLower = 0;
}
// specify size of vector
// postcondition: vector of size items constructed
lbvector(int size)
{
assert(size >= 0);
myCapacity = size;
myList = new Item [size];
assert(myList != 0);
}
int capacity( ) const
{
return myCapacity;
}
private :
Item * myList; // the array of items
int myCapacity; // # things in vector (array), 0,1,...,(myCapacity-1)
int myUpper; // highest legal index
int myLower; //lowest legal index
// aborts with appropriate message if index is not in appropriate range
// use std:: to access names in std namespace
void checkIndex (int index) const
{
if (index < 0 || myCapacity <= index) {
std::cerr << "Illegal vector index: " << index
<< " (max = " << myCapacity-1 << ")"
<< std::endl;
assert(index >= 0);
assert(index < myCapacity);
}
}
};
and here my driver
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include "lbvector.h"
using namespace std;
int main()
{
lbvector<int > example();
cout << "Hello world!" << endl;
cout << example.capacity();
return 0;
}
So, here is my problem: When I use an int in the constructor (i.e. 5) it will work and print out 5. BUT, when I use an empty constructor like shown above, it doesn't work and I get the error message
error: request for member 'capacity' in 'example' , which is of non-class type 'lbvector<int>()
What am I doing wrong? Thanks.
Last edited on Nov 18, 2012 at 11:29pm UTC
Nov 18, 2012 at 11:35pm UTC
This
lbvector<int> example();
is a declaration of a function that has return type lbvector<int> and has no parameters.
You should write
lbvector<int> example;
Nov 18, 2012 at 11:37pm UTC
Ahhhhh! Thanks. I knew it was something dumb...
Topic archived. No new replies allowed.