0

I'm trying to make automatic generation of a value in a class in C++.

This is Shape.h

#pragma once
class Shape
{
public:
    Shape();
    ~Shape();
    // Return ID of the Shape
    virtual int getId();
    // Return area of the Shape
    virtual double getArea();
protected:
    static int _id;
    double _area;
    // Compute the area of the shape
    virtual void compArea() = 0;
};

And this is Shape.cpp

#include <iostream>
#include "Shape.h"


Shape::Shape()
{
_id++;     //ID is incremented in every instance
_area = 0.0;
}


Shape::~Shape()
{
    std::cout << "Distruttore Shape" << std::endl;
}


// Return ID of the Shape
int Shape::getId()
{
    return _id;
}


// Return area of the Shape
double Shape::getArea()
{
    return _area;
}

And when I compile I receive:

error LNK2001: external symbol "public: static int Shape::_id" (?_id@Shape@@2HA) unresolved

What am I doing wrong?

Thanks for help :)

Fededark
  • 15
  • 4
  • I think you want something like auto-generated id, in case for that, you should provide another class member variable like, `int real_id`, then on the constructor side, assign it to the static one `real_id = _id++;`, then this one should be the return variable of `getId()` – mr5 May 06 '14 at 12:52

1 Answers1

6

Define the static variable in cpp file:

int Shape::_id; 

You should do this in the same namespace in which you've defined Shape.

Note that static int _id; inside the class is called declaration, which means, it is an announcement to the compiler that _id as variable of type int exists somewhere — where exactly? the compiler doesn't bother with this question.The announcement/declaration itself doesn't make the variable to exist in memory. To make it exist in the memory, you need to define it.

Also note that the compiler needs only the declaration and the linker needs the definition — i.e the linker asks the question "where exactly?" which is why it needs the definition which ensures its existence.

Nawaz
  • 353,942
  • 115
  • 666
  • 851