C++ :: Static Variable Inside A Member Function

Jul 20, 2013

Say you had:

class Foo{
public:
//...
void funky();

[Code] .....

Would each instance of Foo create a new counter variable, or would it remain the same for all of them, i.e. baz.funky() would always use the same counter variable? What if the class was a template?

View 3 Replies


ADVERTISEMENT

C++ :: Undefined Reference Error When Accessing Static Variable Inside Member Function

Feb 10, 2013

I am modifying a set of static variables inside of the class's member function. The static variables are private. An example of what I'm doing is as below,

utilities.h
-----------
class utilities {
private:
static int num_nodes;

public:
void parse_details(char* );

[Code] ....

I get a compilation error in the function void utilities::parse_details(char* filename)

which says: undefined reference to `utilities::num_nodes'

compiler: g++

View 2 Replies View Related

C++ :: Accessing Non-static Members Inside Static Member Functions

Sep 11, 2013

What are the workarounds for accessing the non-static member variables of some class(Say A) inside static member functions of another class(Say B)? I am coding in c++. Class A is derived with public properties of class B. Any pointers?

View 7 Replies View Related

C++ :: Static Variable In Member Function

Aug 27, 2014

I need to keep a static variable in a member function of a class that I have many objects of. I've had some trouble with it, and when I read up I found that such variables are static across all instances. Is there any way around this?

View 3 Replies View Related

C/C++ :: Difference Between Declaring Static Variable Inside And Outside Of Main

Apr 6, 2012

I want to know

prog1.c
#include<stdio.c>
static int c=6;
int main() {
/*code*/
}

prog2.c
#include<stdio.h>
int main(){
static int c=10;
}

what would be the difference between these two program in the fuctioning of static keyword ?

View 1 Replies View Related

C++ :: Static Constant Member Variable

Jun 6, 2013

What is the problem with the following code is? It compiles with Visual C++ 2012 but does not with g++:

//a.h

#ifndef Loaded
#define Loaded
using namespace std;
class MyClass{
public:
static const int MyStaticValue = 200;

[Code] ....

If I try to compile this using the command

g++ a.cpp b.cpp

I get an "undefined reference to 'MyClass::MyStaticValue'" error for the line "A = MyClass::MyStaticValue;" in main(). The strange thing is that if I change the line to "A = (int) MyClass::MyStaticValue;" it works fine and the output is

200
200

as expected.

The code also compiles under g++ if I move the defintion of MyStaticValue from a.h to a.cpp by const int MyClass::MyStaticValue = 200;

View 5 Replies View Related

C :: Set Struct Member Variable For Structure Inside Def

Mar 12, 2014

This is with Linux gcc

Code:
typedef struct _a
{
int id;
} a;
typedef struct _b
{
a my_a;
my_a.id = 1; // error: expected specifier-qualifier-list before "my_a"
} b;

I get error: expected specifier-qualifier-list before "my_a"

I must set the id for the kind of struct created inside the struct def because main() will be casting based on this id. Thats how I will know which structure b contains by it's id, there could be hundards of different structs with different values I will cast to the correct one and know it's members by it's id. How do I ?

View 10 Replies View Related

C++ :: Call Member Function Inside Another Member Function?

Mar 21, 2013

If I wanted to call a member function inside another member function, how would I do that, if it's possible?

For example, if I have Find(int key) defined already and wanted to call it while i was overloading operator+.

View 2 Replies View Related

C++ :: Getting Static Member / Function Errors

Mar 8, 2014

What am I doing wrong with static members and methods here?

compiler errors:

1>test.obj : error LNK2005: "private: static int Test::count" (?count@Test@@0HA) already defined in main.obj
1>c:usersjamesdocumentsvisual studio 2013Projectsstatic_testReleasestatic_test.exe : fatal error LNK1169: one or more multiply defined symbols found
test.h
#ifndef TEST_H_
#define TEST_H_
class Test {

[code]....

View 4 Replies View Related

C++ :: Function Pointer To Non-static Class Member

Aug 19, 2014

I have the following problem: I am using NLOpt for optimization. The API provides functions to set the objective. This is done as follows:

double objective(const vector<double> &x, vector<double> &grad, void *data)
{
return x[1]*x[0];
}
int main(){
nlopt::opt opti(nlopt::LD_MMA,2);
opti.set_min_objective(objective,NULL);
vector<double> x(2);

[Code]....

Now I want to make the function objective a member of a class:

class Foo {
public:
double objective(...){..}
};

How can I give this method to opti.optimize? If I make objective static I can use

opti.optimize(Foo::objective,NULL);

but I do not want to have a static member. Is it possible to create an object of type Foo and give it to opti.optimize?

View 1 Replies View Related

C++ :: Non Constant Member Function Being Called Inside Constant Member Function?

Dec 28, 2012

#include <iostream>
class Hello {
public:
void Test() {

[Code].....

As i know a non-constant member function cant be called inside a constant member function but how the above code has been compiled successfully and giving the expected result .

View 5 Replies View Related

C++ :: Fixed Point Implementation - Calling A Static Member Function

Apr 25, 2013

I am doing fixed point implementation in c++ which is done by the following code

#ifndef __fixed_point_header_h__
#define __fixed_point_header_h__
#include <boost/assert.hpp>
#include <boost/static_assert.hpp>
#include <boost/operators.hpp>
#include <limits>

[Code] ....

I am getting the error ambiguous overload for âoperator<â in âbeta < ((-5.0e-1) * pi)â

I know the problem the static member function cannot access the members and objects of structs. am i right?

and how to solve this problem, do i need to implement the cossin_cordic function as a non member function.

View 14 Replies View Related

C++ :: Difference Between Static Local Variable And Static Global Variable?

Aug 5, 2013

Here is the code,

Code:
class A {
};
A& CreateObject() {
static A a;
return a;
} static A aa;
int main() {
return 0;
}

So is there any difference between a defined in CreateObject and aa?

View 6 Replies View Related

C# :: Static Method Inside Non-static Class

Aug 22, 2014

Have following code:

class Program
{
static void Main(string[] args)
{

[Code]....

My question according to what i just wrote:

1. Is that mean that Do() is only available for use by Dog itself because Dog is 'oryginal' Dog, and if i create new dogs - instances of oryginal Dog (dog1, dog2 ...) they cant access because Do is only available fo 'oryginal' one? Is that correct thinking?

2. If i would want to have something common (e.g value) for all dogs is that good way to create static field/method for Dog instead of non-static once then all instances of Dog would access Dog static member to get/change it? Just stupid example: static method GetAmountOfLegs() which return 4 Then all instances can take/call that value from Dog. Is that correct thinking?

View 2 Replies View Related

C++ :: Virtual Can Only Exist In Non-static Member Function - Field Has Incomplete Type Void

Dec 5, 2014

I'm writing a class "Property" for a program that manages different types of properties. This is my .h for y base class. I was trying to write a virtual void function to convert different children classes to strings that can be displayed, but Xcode is freaking out.

I had it as:

virtual void toString()= 0;

and it gave me an error message: "Virtual can only exist in non-static member functions" and "field has incomplete type 'void'"

I changed it to:

virtual string toString() = 0;

and the error message didn't change.

Is this an issue with Xcode or did I do something wrong? Even after changing it to string it told me that it "has incomplete type 'void'"....

View 1 Replies View Related

C++ :: Static Variable And Function With Template

Jul 18, 2012

I try to create small project in order to better understand how key word static works with templates . However some compiles errors crush my plan.

1>------ Build started: Project: 4.2b - Ex 1. Static Variable for Array Def Size. Templates, Configuration: Release Win32 ------
1> main.cpp
1>c:all myс++ha level 6solution level 6solution level 64.2b - ex1. static variable for array def size. templatesarray.cpp(40): error C2724: 'Array<Type>:efaultSize' : 'static' should not be used on member functions defined at file scope

[Code] .....

View 7 Replies View Related

C++ :: Creating A Variable Inside Function Arguments

May 15, 2013

In the following code:

#include <iostream> // For stream I/O
using namespace std;
int function(int a) {
return a;
}
int main() {
function(int b);
}

Why is creating a variable inside the function argument list not allowed. Any reason other then for the language syntax or just for the language syntax?

View 19 Replies View Related

C++ :: Member Variable Aliasing A Function?

Dec 26, 2014

So, one can do stuff like this using #defines:

#include <iostream>
#include <array>
#define x arr[0]
#define y arr[1]
#define z arr[2]
class Point {

[code]....

... that is, to be able to reference the same data by "member variables" as by referencing a stl container. But defines are the devil's work - adding in a "#define x arr[0]" is a dangerous statement. I'd really like some nice clean C++ method (C++11 or C++14 are just fine) to do this without defines, but so far I'm drawing a blank. If arr wasn't an STL container, if we just wanted a pointer-based array, I could do it this way:

class Point
{
...
float x __attribute__ ((aligned (sizeof(float))));
float y __attribute__ ((aligned (sizeof(float))));
float z __attribute__ ((aligned (sizeof(float))));
float*const arr = &x;
};

... but you obviously can't do that if arr is an STL container.

The best I've come up with is to make x, y, and z function pointers, but then you can't call them like p.x, you have to call them like *p.x(), it's not very clean and I'd expect some added overhead. One could go even uglier and make x, y, and z be instances of some custom class with overridden operators that reference arr[], but that seems like it'd be just getting ridiculous in terms of overhead (both coding and performance)

View 4 Replies View Related

C/C++ :: Pointing Variable To A Member Function Outside A Class

Apr 13, 2012

In C++, how do i call a method member of class A from a class B, using a pointer. By the way Class A and B are of different types.

I read that when a pointer is pointing to member function it can only point member functions within the class. But how can i point to a member function outside the class.?????

for example

class A {
public:
int add(int x) {
return x+x;

[Code] .....

View 1 Replies View Related

C/C++ :: Passing Member Functions Member Variable To Another Variable

Aug 31, 2014

So I have a class object that contains the private member variable spot and the public member function MoveLock. Within MoveLock, is a member variable called numbers that holds the place where a user is on a "lock knob". Now, what I'm trying to accomplish is that whenever the user turns the "knob" in the wrong direction, the position is updated with that current numbers so that the clicks needed to unlock the first state is also updated. But I get these errors:

Error E2096 C:Users...switchtest.cpp 34: Illegal structure operation in function main()
Error E2294 C:Users...switchtest.cpp 39: Structure required on left side of . or .* in function main()

Ultimately, what I have in main() is a piece of what I'm going to implement in a class member function. I'm also thinking about moving the if else statements out of the for and creating a second one for the else portion.

#include <iostream>
#include <windows.h>
#include <iomanip>
using namespace std;
HANDLE inKeys = GetStdHandle(STD_INPUT_HANDLE);
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);

[code]....

View 10 Replies View Related

C++ :: Static Type Dispatch With Structs Inside Classes?

Oct 15, 2013

I wanted to ask if it is somehow possible to do:

Code:
class RaspberryPi: public Singleton<RaspberryPi> {
private:
static const DeviceInfo GPS;
template<typename Register_t>
auto ReadGPS(Register_t& Register) -> void

[Code] ....

There are two limitations I am facing:

First, it seems that anything that is part of a struct cannot be a compile-time expression. It's a nice way to group information, so it would be nice to have.

Secondly, it seems that all compile-time expressions cannot be inside a class (at least according to VC++), which means I have to move them to global level, but while it can be done, I don't really want to do it, because it's a platform detail.

In this case, static type dispatch would be nice to have because I have a function

Code:
template<typename Register_t>
auto ReadBus(Platforms::DeviceInfo Device, Register_t& Register) -> void {
switch (Device.Bus)

[Code] .....

There are two types of registers. With runtime dispatch, I get disgusting errors such as "could not deduce template arguments, blah blah" if some object doesn't have the required interface (i.e., don't have overloads for both register types). So the workaround would be to add two overloads and use something like asserts to stop invalid code from running, but it would be so nice to only allow correct code to compile and not get scary error messages.

View 5 Replies View Related

C++ :: Initializing Static Member Just Once Throughout

Jul 24, 2014

Here I'm trying to initialize PersonFactory::ethnicSurnames just once for the entire run of the program:

#include <iostream>
#include <string>
#include <vector>
#include <array>

enum Country {India, China, France, NumCountries}; // plus many other countries
struct School {}; struct Mall {}; struct HockeyArena {};

[Code] ....

Output:

PersonFactory::initializeEthnicNames() called
Carrying out the initialization...
PersonFactory::initializeEthnicNames() called
PersonFactory::initializeEthnicNames() called
PersonFactory::initializeEthnicNames() called
PersonFactory::initializeEthnicNames() called
numberOfTimesInitialized = 1

As you can see, even though five PersonFactory objects were constructed, the ethnicNames initialization only occurred once, as desired. However, there are some issues with my method. First of all, the use of the comma operator is ugly in my opinion. But fashion statements aside, PersonFactory::initializeEthnicNames() is still called multiple times, which is not good, even though it correctly avoids reinitializing ethnicNames after the first call. Also, I now forever get the annoying compiler warnings that the bool namesInitialized is never used, which is true, thus wasting a small bit of memory. And finally, I cannot declare ethnicNames const now, and it is supposed to be const. Any better way to accomplish what I'm trying to do?

By the way, the reason why I don't initialize ethnic names outside the class as is normally done for static data members (and that would indeed allow me to declare it const) is because it would get messed up if I later change the order of the elements in enum Country. Hence actual lines of initializations I think are needed. And I do want ethnicSurnames inside PersonFactory, because I feel it really does belong there. Also, PersonFactory is not to be Singleton, because it has data members that depend on some parameters in its constructor (e.g. geographic location).

View 5 Replies View Related

C++ :: Store A Reference Variable As Member Variable Of Interface Object

May 1, 2013

I am having trouble compiling my interface. I am trying to store a reference variable as a member variable of the interface object. Compiler says that the variable has not be initiated correctly.

LCD inherits from VisualInterface which is expecting a DisplayDriver object to be passed in (DisplayDriver is another interface, but thats not important).

I pass the displayDriver object in when LCD is instantiated in maininterfaces.zip

I was pasing it before as a pointer but was told that this could cause me problems with memory leaks and a reference was better, but now I cant seem to get it to compile.

View 11 Replies View Related

C++ :: Static Constant Member Initialization

Jun 5, 2013

I am having a problem concerning a static const member variable I want to use to set a certain property of my class during development time. The question actually concerns proper implementation as I do have a solution that "works" at least. The variable should denote the size of a member array which I don't want to allocate on the heap due to serious performance issues. So here is my code:

//MyClass.h
class MyClass{
public:
static const int MyArraySize = 256;
private:
int MyArray[MyArraySize];
};

This works but it's not nice for two reasons:

1) It doesn't separate interface from implementation. I would prefer to define the variable in the corresponding .cpp file but it doesn't work:

//MyClass.h
class MyClass{
public:
static const int MyArraySize;

[Code] .....

If I delete the line int MyArray[MyArraySize]; the above code works but when I use it to define the size of the array I get a "constant expression expected" error for the line int MyArray[MyArraySize]; which makes sense as the compiler does not know the value of MyArraySize when he reaches int MyArray[MyArraySize]; and therefore can not allocate the memory. Of course I can move MyArray to the heap like that:

//MyClass.h
class MyClass{
public:
static const int MyArraySize;
static const int MyValue;

[Code] .....

But as I mentioned before this causes a remarkable loss of performance.

Something like the following does not work:

//MyClass.h
class MyClass{
public:
static const int MyArraySize = (int) pow(2, 8);
private:
int MyArray[MyArraySize];
};

This gives a "constant expression expected" error for the line static const int MyArraySize = (int) pow(2, 8);

Interestingly the following code works:

//MyClass.h
class MyClass{
public:
static const int MyValue;
};

//MyClass.cpp
#include "MyClass.h"
const int MyClass::MyValue = (int) pow(2, 8);

So if I use pow outside of the class definition I get no errors. Is there any solution to those problems? So what I want is:
1) Don't allocate the array on the heap
2) Separate interface from implementation
3) Being able to use functions like pow to define MyArraySize
4) Not use global variables

View 19 Replies View Related

C++ :: Invalid Use Of Non-static Data Member?

May 25, 2014

I am getting this error invalid use of non static data member.my code looks something like this: i have a main.cpp and 2 class files with respective .h files, say one class file is named human (so i have human.cpp and human.h) and stats (so i have stats.cpp and stats.h) in my stats.h file, i have a double array: double HumanF[10][12] with everything filled in.then in my human.h file i just have a bunch of integers. human.cpp has formulas in it that use numbers from the double array i mentioned. for example

Human::Human() {
constant (this is a double i made in human.h) = (1+Stats::HumanF[0][0]);
i (another double) = pow(constant, ylvl);
(ylvl is also an int I made in my header file)
yhp = i*137;
}

View 11 Replies View Related

C++ :: How To Use Functor As Static Constexpr Member

Jan 19, 2014

How does one use a functor as a static constexpr member? I had this basic functor for a class:

struct functor{
short operator()(char c)const{return c-'0';}
};

And in the class, I use it as a static constexpr member:
class Foo{
public:
//...
private:
static constexpr functor k_funky = functor();
};

During the linking stage, I kept getting "undefined reference to 'Foo::k_funky'". So then I tried declaring the functor's constructor and operator function constexpr:

struct functor{
constexpr short operator()(char c){return c-'0';}
constexpr functor() = default; //This counts, doesn't it?
};

But I received the same error.

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved