I have a member static const int x defined in class Foo, and I'm passing
it by reference, and by value elsewhere (see the code below). Passing it
by value works, but by reference it doesn't: it thinks x is undefined.
Could someone explain what's going on here? Why can't I pass a static
const member by reference?
This is how I compile it:
g++ -g -Wall sample_main.C # g++ -v 4.0.1
/tmp/ccUJx59K.o(.gnu .linkonce.t._ZN 3Foo12bad_funct ionER3Bar[Foo::bad_functi on(Bar&)]+0xa): In function `Foo::bad_funct ion(Bar&)':
/tmp/STATICCONST/sample_main.C:1 8: undefined reference to `Foo::x'
collect2: ld returned 1 exit status
#include <cstdlib>
using namespace std;
class Bar
{
public:
void good(const int a) {}
void bad(const int & a) {}
};
class Foo
{
public:
static const int x=0;
void good_function(c lass Bar & B){ B.good(x); }
void bad_function(cl ass Bar & B) { B.bad(x); }
};
int main(int argc, char * argv[])
{
Foo F;
Bar B;
F.good_function (B);
F.bad_function( B);
return 0;
} 13 2589
Amadeus W. M. wrote:
.... class Foo { public: static const int x=0;
void good_function(c lass Bar & B){ B.good(x); } void bad_function(cl ass Bar & B) { B.bad(x); } };
Add this:
const int Foo::x;
Amadeus W. M. wrote: I have a member static const int x defined in class Foo, and I'm passing it by reference, and by value elsewhere (see the code below). Passing it by value works, but by reference it doesn't: it thinks x is undefined. Could someone explain what's going on here? Why can't I pass a static const member by reference?
You can but the difference is that when you pass by value the compiler
substitutes the value 0 so storage for the actual variable is not
needed. But when you pass by reference you need an actual variable which
you have failed to declare (what is in the class is a definition not a
declaration).
You need to add the declaration to sample_main.C as Gianni showed.
john
John Harrison wrote: Amadeus W. M. wrote:
I have a member static const int x defined in class Foo, and I'm passing it by reference, and by value elsewhere (see the code below). Passing it by value works, but by reference it doesn't: it thinks x is undefined. Could someone explain what's going on here? Why can't I pass a static const member by reference?
You can but the difference is that when you pass by value the compiler substitutes the value 0 so storage for the actual variable is not needed. But when you pass by reference you need an actual variable which you have failed to declare (what is in the class is a definition not a declaration).
You need to add the declaration to sample_main.C as Gianni showed.
john
Sorry, got the words definition and declaration completely the wrong way
round in the above explanation.
john
On Sat, 17 Sep 2005 11:14:56 -0700, Gianni Mariani wrote: Amadeus W. M. wrote: ... class Foo { public: static const int x=0;
void good_function(c lass Bar & B){ B.good(x); } void bad_function(cl ass Bar & B) { B.bad(x); } };
Add this:
const int Foo::x;
Of course, this works, but I thought only non-integer static consts
require this. I thought static const int can be defined inside the class.
And it can be defined inside the class, as long I don't pass it by
reference.
On Sat, 17 Sep 2005 18:22:51 +0000, John Harrison wrote: Amadeus W. M. wrote: I have a member static const int x defined in class Foo, and I'm passing it by reference, and by value elsewhere (see the code below). Passing it by value works, but by reference it doesn't: it thinks x is undefined. Could someone explain what's going on here? Why can't I pass a static const member by reference? You can but the difference is that when you pass by value the compiler substitutes the value 0 so storage for the actual variable is not needed. But when you pass by reference you need an actual variable which you have failed to declare (what is in the class is a definition not a declaration).
But isn't x supposed to be _defined_ (hence allocated and initialized)
when I say
static const int x=0; // inside class Foo;
?? Is it that the compiler is trying to be smart, or am I not complying
with the standard?
You need to add the declaration to sample_main.C as Gianni showed.
john
"Amadeus W. M." <am*******@cabl espeed.com> wrote in message
news:pa******** *************** *****@cablespee d.com...
<snip> #include <cstdlib> using namespace std;
class Bar { public: void good(const int a) {} void bad(const int & a) {} };
class Foo { public: static const int x=0;
void good_function(c lass Bar & B){ B.good(x); } void bad_function(cl ass Bar & B) { B.bad(x); } };
int main(int argc, char * argv[]) { Foo F; Bar B;
F.good_function (B); F.bad_function( B);
return 0; }
This code works fine under VS8 ;/
On Sat, 17 Sep 2005 14:23:44 -0500, Jon Slaughter wrote: "Amadeus W. M." <am*******@cabl espeed.com> wrote in message news:pa******** *************** *****@cablespee d.com... <snip> #include <cstdlib> using namespace std;
class Bar { public: void good(const int a) {} void bad(const int & a) {} };
class Foo { public: static const int x=0;
void good_function(c lass Bar & B){ B.good(x); } void bad_function(cl ass Bar & B) { B.bad(x); } };
int main(int argc, char * argv[]) { Foo F; Bar B;
F.good_function (B); F.bad_function( B);
return 0; }
This code works fine under VS8 ;/
Thank you, maybe I should ask on a g++ newsgroup then.
In fact, here's what I want to do: I have 1 header file Foo.H included in
two source files sample_main.C and foobar.C. The definition of Foo::x
should really be in Foo.H.
// file Foo.H:
#ifndef _FOO_H
#define _FOO_H
#include <cstdlib>
using namespace std;
class Bar
{
public:
void good(const int a) const {}
void bad(const int & a) const {}
};
class Foo
{
public:
static const int x=0;
void good_function(c onst Bar & B) const { B.good(x); }
void bad_function(co nst Bar & B) const { B.bad(x); }
};
const int Foo::x;
#endif
// file foobar.C:
#include <cstdlib>
#include "Foo.H"
using namespace std;
void foobar()
{
Foo F;
Bar B;
F.good_function (B);
F.bad_function( B);
}
// file sample_main.C
#include <cstdlib>
#include "Foo.H"
using namespace std;
extern void foobar();
int main(int argc, char * argv[])
{
Foo F;
Bar B;
F.good_function (B);
F.bad_function( B);
foobar();
return 0;
}
g++ sample_main.C foobar.C
gives (understandably ) multiple definition of Foo::x. Of course, if I put
const int Foo::x;
in sample_main.C, it works, but I it's more natural that the definition of
Foo::x should be in Foo.H.
If I don't put const int Foo::x; anywhere (neither in main nor in Foo.H),
it works, as long as I don't call Foo::bad_functi on() i.e. as long as I
don't access Foo::x by reference.
If, on the other hand, I make Foo a template class and define
template <class DummyType>
const int Foo<DummyType>: :x;
outside Foo in Foo.H, it works (no multiple definition of
Foo<DummyType>: :x, no undefined references). I would rather not make Foo
a template class though, if I don't have to.
Is there another way? Thanks!
Amadeus W. M. wrote: In fact, here's what I want to do: I have 1 header file Foo.H included in two source files sample_main.C and foobar.C. The definition of Foo::x should really be in Foo.H.
// file Foo.H: #ifndef _FOO_H #define _FOO_H
#include <cstdlib> using namespace std;
class Bar { public: void good(const int a) const {} void bad(const int & a) const {} };
class Foo { public: static const int x=0;
void good_function(c onst Bar & B) const { B.good(x); } void bad_function(co nst Bar & B) const { B.bad(x); } };
const int Foo::x;
#endif
// file foobar.C: #include <cstdlib> #include "Foo.H"
using namespace std;
void foobar() { Foo F; Bar B;
F.good_function (B); F.bad_function( B); }
// file sample_main.C #include <cstdlib> #include "Foo.H"
using namespace std;
extern void foobar();
int main(int argc, char * argv[]) { Foo F; Bar B;
F.good_function (B); F.bad_function( B);
foobar();
return 0; }
g++ sample_main.C foobar.C
gives (understandably ) multiple definition of Foo::x. Of course, if I put const int Foo::x; in sample_main.C, it works, but I it's more natural that the definition of Foo::x should be in Foo.H.
Well that is tough, C++ says it should be in sample_main.C (or foobar.C). If I don't put const int Foo::x; anywhere (neither in main nor in Foo.H), it works, as long as I don't call Foo::bad_functi on() i.e. as long as I don't access Foo::x by reference.
That is true, although I'm not sure the C++ standard guarantees that.
If, on the other hand, I make Foo a template class and define
template <class DummyType> const int Foo<DummyType>: :x;
outside Foo in Foo.H, it works (no multiple definition of Foo<DummyType>: :x, no undefined references). I would rather not make Foo a template class though, if I don't have to.
Well that is because the rules for templates are different. Template
code *always* goes in header files.
Is there another way? Thanks!
No, unless an enum would suffice.
class Foo
{
enum { x = 1 };
};
In the old days you would have been required to define and initialise
Foo::x in a .C file. Since standardisation you can now initialise Foo::x
in the header file, but you are still required to define it in a .C file.
john This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: John Stiles |
last post by:
I have written some pretty simple code which works great in Dev Studio
and CodeWarrior, but gcc is giving me link errors. Here is what I've
been able to distill it down to:
namespace Private {
template <class T> struct lengthof;
template <class T, size_t N> struct lengthof<T> { static const
size_t array_size = N; };
}
|
by: Srini |
last post by:
Hello all,
I was just wondering about this. A const member function guarantees
constness of the object within the function body. But there's no way
for a member function to guarantee the constness of static members. Is
there a way to do that? Also, is there a way for a static member
function to guarantee constness of static members?
TIA
Regards,
|
by: Ashwin |
last post by:
hi guys,
i have overloaded the << operator.as shown below.
ostream& operator<<(ostream &out, const student &a)
{
out<<a.idno;
out<< " " ;
// out<< a.name;
out<< " " ;
// out<< a.marks << endl;
|
by: Gary Wessle |
last post by:
Hi
in the attempt below, I intend to use 2 derived classes whose objects
c'tor fires a base class method which build a string "main_menu" which
is a concatenation of the strings for each derived object c'tor
argument. ok, let me explain in a different language; but before, here
is the expected output
preform Thread task.
preform non-thread task.
|
by: tbringley |
last post by:
I am a c++ newbie, so please excuse the ignorance of this question.
I am interested in a way of having a class call a general member
function of another class.
Specifically, I am trying to write an ordinary differential equation
class that would solve a general equation in the form:
dx/dt = f(x,t).
The ode class shouldn't know anything about f, except how to call it.
| |
by: mati |
last post by:
Hi
The following code works:
#include <vector>
class C {
private:
static const int m_static = 2;
public:
void f(const std::vector<int>& v)
|
by: Bram Kuijper |
last post by:
Hi all,
I am trying to resize a vector of objects (MyObj below), which contain
references to other objects (OtherObj, see below). However, apparently
somewhere in the resize operation an assignment is done of the
referenced OtherObj object (according to the compiler messages). This is
strange, since the referenced OtherObj is initialized using member
initialization lists. Anyone a clue?
thanks,
|
by: Subodh |
last post by:
Hi All,
In C++ we could pass a constant reference to a function so that the
target function could not modify the objects passed
eg. const classA & dummmyfunction(const classB)
similar thing was valid for objects passed with pointer to constant
objects
In C++/CLI is there any way for imitating this, I want to pass
arguments to and return value from my member function as a constant
|
by: puzzlecracker |
last post by:
How can I pass a reference to a method as constant?
I tried the following:
Function(const Foo f) or Function(readonly Foo f)
Also, How to declare local variable to be constant
const Foo foo or readonlyFoo f?
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |