C++ :: Why Vptr Is Not Static
Oct 14, 2013So, even though the virtual pointer is constant across objects of class why cant it be made as static. Why each derived instance is having the pointer to vtable.
View 4 RepliesSo, even though the virtual pointer is constant across objects of class why cant it be made as static. Why each derived instance is having the pointer to vtable.
View 4 RepliesFrom my book:
"A static function might have this prototype:
static void Afunction(int n);
A static function can be called in relation to a particular object by a statement such as the following:
aBox.Afunction(10);
The function has no access to the non-static members of aBox. The same function could also be called without reference to an object. In this case, the statement would be:
CBox::Afunction(10);
where CBox is the class name. Using the class name and the scope resolution operator tells the compiler to which class Afunction() belongs."
Why exactly cant Afunction access non-static members?
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 RelatedHave 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?
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?
I have a class where I'm trying to create two static maps. I know I haven't separated the implementation from the declaration. This is how I'm required to program at the moment.
My example class that I'm trying to compile looks like this:
#include <map>
#include <string>
class Foo {
[Code]....
I keep getting compiler errors, though, saying:
invalid use of qualified-name Foo::map1
and
invalid use of qualified-name Foo::map2
I can't initialize these maps explicitly; in my real program they're created by reading in a few different files' data on startup. I need to be able to access the maps throughout my entire application, and I don't want to be required to read in the same data file over and over again.
how static maps can be created properly, or failing that explain another methodology I could use to make them available to my entire application?
I have the following scenario: I plan to have an xml configuration file.I have a trader that lunch few strategies, each have different configurations. I plan to have all configuration reside in the same file as different nodes.
Now I want that each strategy will hard code the name of node it will loop up for its parameters. Since those paramters are requered for the init and I use DI (configuration are passed in the constructor) I want to make it static.
So this would be something like.
public class Strategy: Base_strategy{
public const string _conf_name = "XXX";
public static string get_conf_name(){
[Code]....
Since other people will code strategies, I want each strategy to implement this static function. I wanted to do this in an interface so that anyone coding new strategy,implementing the base strategy will have to code this static function as part of the contract.
I am just wondering what the best practice is for when to use static classes (by static class, I mean a class which has only static attributes and functions).
If you are creating more than one independent object of a particular class, then obviously this should not be static because each object will be the same. But what about the case when you know that you will only ever need one instance of a class? On its own, does this mean that you should create it as a static class?
Personally, I use static class when I want its member attributes and functions to be available globally, which I think is fine. However, I am not sure about the case when I know that only one object will be created - should this be a static class or not?
I have the codes for the functions: "Given the functions that we have discussed and defined in the class and the code that we have created, create the code for the Delete Node function and the Search function. Create an application that will incorporate all the functions that we have discussed and the new ones that you need to create. The application should allow the linked list to be built initially from a text file. The application should then allow for the user select an operation to perform. The acceptable operations are
- to search for an item
- to delete an item
- to enter a new item
- to exit the application
After the initial build and loading of data from the textfile, the application should print a listing of each item in the list and the node that it is located in. after a delete or insert, the application should display an output of the list again showing each item in the list and the node that it resides in.
The data item for this problem will be the inventory structure that we created in class and the data is in the inventory file that you already have downloaded."
I was exploring static variable by writing code snippets. I tried below code and it ended up throwing error saying "error: storage class specified for parameter 'b'"
Why static cannot be used in func() ?
Code:
int main() {
int a;
a=5;
func(a);
printf("%d",a);
return 0; }
void func(static int b)
{b=6;
printf("%d",b); }
I am trying to refresh my memory here as I did some studies many years ago but the results elude me.Also todays c/c++ compilers may have better optimizations.Say I have a static library that includes three obj modules.Each of these object modules has a number of functions. These functions do not reference any other functions within the obj module.My main app links this library but only references one function from each of the object modules.
Question: Are the complete contents of each module linked into my main app or are todays linkers smart enough to just link the functions used?
If I have a static variable in a class e.g. a pointer to another class like this: (B is another class)
class A {
public:
static B* cB;
};
Then I set that variable and create multiple instances of class A like this:
A::cB = new B;
As = new A[Number];
Then will the value of cB be the same across all instances?
I cannot pass the class pointer in the constructor as I need to create an array of instances. I tried this method but I get linker error.... unresolved external.
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).
can i have 1 static variable with instance different value?
View 3 Replies View RelatedIf i declare 2 variables like this static int first, second; will both of them be declared static or will only first be declared static and second a regular variable?
View 5 Replies View Relatedso i was trying to find out how to do unbuffered input in linux and came across this class: [URL] . i didnt like how i had to create a new instance of it each time i wanted to use it, so i made the functions static and renamed the class to Buffer. i could then call it like this: Buffer::On(); Buffer::Off();. My question is, when doing something like that where the class consists of two functions that can exist indepently of another, which is better: a class like what i did or wrapping it in a namespace?
View 3 Replies View RelatedIs it more expensive to use too many static variables instead of ordinary variables? If yes, then how?------------This is a topic given to me to find out about and I don't even know what are static variable except that they live throughout the life of program
and only disadvantage of using static variable instead ordinary variables in my mind is just they will use memory even when we don't need them
I have a class containing a map member that I want to initialize at declaration time. I know I can do it in the cpp file but I'm having a problem with the order of initialization (static initialization order fiasco).
My questions are:
Is it possible that the scenario in which, the Test's constructor's implementation and the map initialization instruction are in the same cpp file and constructor is called when the map is not initialized yet, could happen?
Is it possible to initialize the map in class like I did? I get these errors:
in-class initialization of static data member 'std::map<std::basic_string<char>, Test*> Test::a' of incomplete type
temporary of non-literal type 'std::map<std::basic_string<char>, Test*>' in a constant expression
If yes, does this initialization resolve the static initialization order fiasco?
class Test {
public:
static std::map<std::string, Test*> a = {};//this is an error
Test(std::string ID) {
[Code] ....
How to build the static library on my own using visual C++ 2008.
I used the following code to create the header file and cpp of the library.but I am unable to compile due to the following error.
// MathFuncsLib.h
namespace MathFuncs {
class MyMathFuncs {
public:
// Returns a + b
static double Add(double a, double b);
[Code] .....
Error I get while it is compiled :
Error3error C2653: 'MyMathFuncs' : is not a class or namespace name
How to create standalone program. For now I have simple program connecting to MySql Database and when i run it, shows me error, libmysql.dll is missing... When i put libmysql.dll in same folder works. Now my question is, how in code blocks can i compile so i won't require libmysql.dll anymore and be able to use it on any machine.
View 1 Replies View RelatedWhat is the purpose of having static object of the same class.
E.g.
class someObj{
public:
static someObj obj;
};
how the compiler treats this object
I am creating class to be call only once in time so i am trying to implement it static to access it once i created static constructor which will be implemented within first instance of the class. My target is to pass two parameters to onstructor but as i said class should be call only once anyhow i am able to create many instances of that class which i would like to avoid and dont know how firstl i tried to create only one constructor as static with parameters but its not allow then i created static constructor and public contructor which takes two parameters but in this case i am able to create many instances:
public class HeartbeatSupervisor : ICheck
{
private Server _server;
private Protocol _protocol;
/// <summary>
/// HeartbeatSupervisor dd = new HeartbeatSupervisor();
/// </summary>
///
static int k = 0;
static HeartbeatSupervisor()
{
[code]....
inside Program Main i am able multi instances...
HeartbeatSupervisor dd = new HeartbeatSupervisor(new Server(), new Protocol());
HeartbeatSupervisor ee = new HeartbeatSupervisor(new Server(), new Protocol());
I am developing logging class and it loos like below now, my question here is I would like to avoid situation to call this class methods multiple times in same time - as I've read when I have static class or even static method (not exactly whole class) it can be call only once in time. Is this true and whether my class would pass the concept to avoid multi accessing - lets say in case of multithreading case - if one task would try to call statuc method when there is already some other trad using it.
public static class Log {
public static string EngineName { get; set; }
private static List<String> logdata = new List<string>();
public static void LogMessage(string msg, ELogflag flag, string title = "") {
StringBuilder sb = new StringBuilder();
[code]....
And my new Enum:
enum ELogflag {
LOG,
ENGINE,
CRITICAL,
CUSTOM
}
what is static method?
why we can use static method inc#?
I am studying the use of static data into classes and the code below is returning an error ...
#include <iostream>
using namespace std;
class REC {
private:
static int n; //Dado que sera unico na classe e alterado por todos os objetos
[Code] .....
The error:
main.obj:-1: error: LNK2001: unresolved external symbol "private: static int REC::n" (?n@REC@@0HA)
Note: I'm using QT Creator
I'm writing a code generator that produces a function from the strings to the ints. I'll be using the generated code as a "from string to enum" utility. For example:
Code: enum Color {
Red, Green, Blue, Banana
};
// The definition of colorFromString is generated somewhere.
Color colorFromString(const std::string & s);
[Code].....
The implementation of the generated code is a trie. I've seen implementations in the past (including the one at work that I'd like to replace).
Anyway, say you need to compare the region of the string
Code: const char s[] = "holiday"; from index 3 until before index 6 against the string "ida".
I can see two bits of code that my generator could produce. One is
Code: bool hasIda = std::equal(s + 3, s + 6, "ida"); and the other is
Code: bool hasIda = s[3] == 'i' && s[4] == 'd' && s[5] == 'a';
The existing code generator uses the latter method, claiming (I think) that the generated instructions are more efficient on some architectures. Is there any way to determine which is better generally, or do I have to examine the assembly produced on all target platforms?