C++ :: Initializing Const Data Member
Apr 11, 2014
What I need to know is how I can pass an argument to the Book constructor so I can change the const data member Category (with cascading capacity if possible. I also posted some of my set functions for further comprehension.
class Book
{
friend void CompPrice(Book &,Book&); //friend function that has access to the member functions of this class
//The arguments sent to it are by address, and of type the class Book, so that it can have access to its member functions
private: //private data members
[Code].....
View 2 Replies
ADVERTISEMENT
Jan 23, 2015
I have a class that defines a window (a popup dialog of sorts), and I want the name of that window to be constant. The only problem is that the name of the popup needs to match the title of the parent window, and I get the name of the parent in the constructor. So how do I go about defining this member variable to be constant and initializing it with a value in the constructor?
I want to do something like this, but I know this isn't allowed:
/* class.h */
class foo {
public:
foo(*parentWindowPtr);
[Code] .....
I should mention that yes the name of the parent window is const char *, and I would like to keep it this way.
View 4 Replies
View Related
Feb 23, 2015
I have a struct like this:
Code:
struct String{
char* data;
std::size_t size;
};
I would like to be able to create const variables of this type for string literals.
Code:
const String message;
Is there an elegant way to create a const String like this when data is a string literal?
I tried this:
Code:
const char *string_data = "Hello";
size_t string_size = strlen(string_data) + 1;
const String string = {string_data, string_size};
The problem with that is that string.data isn't considered const during the initialization of the String struct so the compiler throws an error. It doesn't feel very elegant to do it like this either way.
Is there an elegant solution to this problem? I would like to avoid making a copy of the string literal.
View 7 Replies
View Related
Oct 17, 2014
My code is here [URL]
void Player::Display() const
{
cout << "
Player Name: " << GetName() <<
"
Grade: " << GetGrade() << "
G.P.A. " << GetGPA() << endl;
}
The problem occurs in here, I get access violations, is there a way to this while keeping Display const or is this code valid and my problem is somewhere else and not being caught in the debugger? I tried to make the return types const - but that didn't work .....
//Getters need const twice for this to work?
const char* Player::GetName() const {return m_name;}
const int Player::GetGrade() const {return m_grade;}
const double Player::GetGPA() const {return m_gpa;}
[Code].....
View 2 Replies
View Related
Sep 27, 2014
i am trying to describe the unusual situation where you declare a class member function with this format:
bool class::function_name(void) const
Specifically where the 'const' follows the parameter list. It is my understanding this is a very useful way of ensuring that whatever code you put in the function definition cannot change any data members of its class.
However I have recently read that this form of declaration should not be used as it leads to less optimized and slower code. Is this correct?
View 3 Replies
View Related
Jan 24, 2013
Code:
class Editor {
// c'tors etc
Gtk::EventBox canvas_event_box;
void functionA();
void functionB() const;
[Code] ....
When I try to compile functionB in Visual C++ it gives me this error:-
glibmm/refptr.h(199) : error C2440: 'initializing' : cannot convert from 'const Gdk::Window *' to 'Gdk::Window *'
Conversion loses qualifiers
And this is the code from glibmm/refptr.h
Code:
// The templated ctor allows copy construction from any object that's castable. Thus, it does downcasts:
// base_ref = derived_ref
template <class T_CppObject>
template <class T_CastFrom>
[Code] .....
I don't actually want to change anything in the member variable canvas_event_box. I just want to be able to call one of its functions from my 'const' member function. Is there any syntax I can use to tell VC++ that I'm not actually changing the variable - just using it.
View 11 Replies
View Related
Apr 18, 2013
class Tracker {
public:
static const int type;
typedef cv_types::CvType<type>::type_t type_t;
};
const int Tracker::type = 1;
gives me the error:
'I' : invalid template argument for 'cv_types::CvType', expected compile-time constant expression
Shouldn't the static const int be a compile time constant?
How would I specify it, so that it works?
PS.: The code works with #define type 1 at the top of the file and without the static const int.
View 3 Replies
View Related
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
Jul 25, 2012
I am learning OOP Console Programming and i got some error in my code;
Here is my code
#include <iostream>
using namespace std;
enum ch {CD,DVD}
class disk {
private :
ch choice;
[Code] ....
I want to compare the enum variable to char c, and cout CD when user press 'c' and cout DVD when user press 'd'. I got error like this :
error : expected ')' before 'c' at first line after public
Note : I must use enum to store value.
View 7 Replies
View Related
May 27, 2014
i want to store reference to a const object in my class as a member variable, as follow:
I basically want a readonly reference to |Data| in Device object.
Code:
class Device {
Device(const QList<QSharedPointer<Data>> & dataList) : _listRef(dataList) {
} protected:
const QList<QSharedPointer<Data>> & _listRef;
}
This does not allow me to initialize _listRef as something like NULL when it is not applicable.Also, i must change all my constructors and its child class to include an initialization of _listRef!!
What is the alternative? Is pointer the nearest? which of the following should be used?
Code:
const QList<QSharedPointer<Data>> * _listRef;
or
const QList<QSharedPointer<Data>> *const _listRef;
or
const QSharedPointer<QList<QSharedPointer<Data>>> _listRef; ????
View 7 Replies
View Related
Oct 30, 2014
Im familiar with fstream and know how to read in data, given that there is one type per line.
But I have a file that has multiple lines each containing a string (an address) and two double values (latitude and longitude).
Looking for support with the logic part of reading in data and initializing them to member variable.
View 1 Replies
View Related
Oct 5, 2013
Are there other ways of calling a const/non-const override? I want to defined some functions in terms of others, particularly accessors which might or might not require constness- in order to not copy & paste code. This is my current solution:
struct dumbArray {
dumbArray(unsigned int size):
m_array(new int[size]){
}
~dumbArray(){
delete m_array;
[Code] .....
View 10 Replies
View Related
Dec 7, 2013
difference between const and static const, more effectively. I know the basic concept of const and static but I need clear explanation of declaring "const" and "static const"
Ex:
const int a;
static const int a;
View 5 Replies
View Related
Jun 19, 2013
Is there any way to cast a non-const variable to const one?
I want to read variable n from file and then use it to declare array "int arr[n]", but because n is non-const, the compiler doesn't allow me to do that.
View 6 Replies
View Related
Jul 13, 2013
So I start thinking about what's the difference between this 2 code
map<const int, float> map_data;
map<int, float> map_data;
But it seems I can't find the difference, is there any difference between this 2 code ?
View 1 Replies
View Related
Mar 28, 2013
I was looking at some linked list material and was wondering something. Can you initialize a data member inside a struct like in C++? i.e.
Code:
typedef struct node
{
int data;
struct node * next = NULL; // this is the line in question
} LLnode;
View 3 Replies
View Related
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
Jul 5, 2013
I have some doubt regarding class data member accessing in another file.Follwing code showing error.
class A://file a.cpp
{
public:
int add;
int sub;
};
//file b.cpp
extern class A
void cal()
{
A::add=A::sub;
}
View 4 Replies
View Related
Aug 18, 2013
can we make a class without any data member ? but it may have member functions ! in c++
View 2 Replies
View Related
Apr 9, 2014
Here's a part of my program. What I need to know is how I can pass an argument to the Book constructor so I can change the const data member Category (with cascading capacity if possible. I also posted some of my set functions for further comprehension.
class Book {
friend void CompPrice(Book &,Book&);
//friend function that has access to the member functions of this class
//The arguments sent to it are by address, and of type the class Book, so that it can have access to its member functions
private:
//private data members
[Code]...
View 1 Replies
View Related
Dec 30, 2013
If I want a class with a vector data member, can I specify it as follows?
std::vector< bool > integers( 101 )
I'm having some problems when compiling code.
View 3 Replies
View Related
Aug 18, 2013
is this possible to make a class without any data member in c++ ?
View 1 Replies
View Related
Dec 21, 2012
Programe #1
// file.h
class File {
public:
static const int var = 9;
};
[Code]....
Program#1 is running fine, but program#2 gives linker error:
error LNK2005: "int GlobalVar" (?x@@3HA) already defined in file.obj
I know the header files are never compiled. Then in the above case, how the compiler knows the definition of variable var, but not able to find the definition of GlobalVar? What is the difference between this two programs?
View 3 Replies
View Related
Jun 22, 2014
So, I've got this class in SDL Player that has, among other things, an SDL_Texture* to hold an image that represents the player on the screen. I'd assume it's good practice to do get() and set() functions for the class; but because textures are handled via pointers, when I write a get() function I end up returning a pointer to an internal resource; which isn't good practice I hear as it "breaks" encapsulation.
Find my code below:
#ifndef PLAYER_H
#define PLAYER_H
#include "SDL.h"
#include "SDL_image.h"
#include "CTexture.h"
class Player {
[Code] .....
View 1 Replies
View Related
Oct 29, 2014
I recently discovered the new - new to me anyway! - feature of modern C++ that allows you to set the initial value of a data member when you declare it:
class CINTWrapper{
private:
int m_iData=0;
};
This even extends to calling member functions that work with initialization I believe:
class CStringWrapper{
private:
wchar_t* Allocate_Array(const int iBufferSize);
wchar_t* m_pString=Allocate_Array(1);
};
At first, this seemed an extremely useful piece of functionality that C++ had been lacking all along. However, the more I thought about it the more it struck me this feature actually undermines one of the principle design elements of the language - that being the Constructor.
As I understand it the primary purpose of the Constructor is specifically to give the programmer a place where it is guaranteed he can always initialize his data members before anything else is done with the class. However, given the new initialization rules this is no longer necessary. So it largely seems to me that Constructors as a whole are no longer necessary either! Copy-Constructors are a special and vital case. Admittedly when I was using them for their intended purpose I hated either the redundancy you had to introduce across multiple Constructors; those with and without arguments and so on, or alternately the fine tuning of helper-functions to do common initialization between these variants. Now however I sort of regret this cast-iron rule has been taken away.
As a last point, I am trying to change the way I think about programming. I am trying to employ more objects than pure C-style ('int' or 'double', etc) data types and especially to move into templates (although absolutely NOT the Hewlett Packard template library!). Given my current understanding of inheritance in particular it seems to me that using pre-initialized data members rather than Constructor-initialization makes object derivation even more complicated, not less so.
View 16 Replies
View Related
Aug 20, 2013
What is the size of object in c++ , if there is no data member in the class ?
View 3 Replies
View Related