473,769 Members | 7,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Constant member of a class

#include <iostream>
using namespace std;

class ConstantMember
{
const int m_const;
public:
ConstantMember( int cons = 10):m_const(con s){}
int getConst() const{ return m_const;}
};

int main()
{
ConstantMember X;//(20);
cout << X.getConst();
return 0;
}

the above is a program that was compiled & linked using g++. Is there
any other way to initialise a constant member variable using
constructor while creating objects?
Jul 4 '08 #1
13 1653
On Fri, 04 Jul 2008 02:08:13 -0700, Anarki wrote:
#include <iostream>
using namespace std;

class ConstantMember
{
const int m_const;
public:
ConstantMember( int cons = 10):m_const(con s){} int getConst() const
{
return m_const;}
};

int main()
{
ConstantMember X;//(20);
cout << X.getConst();
return 0;
}

the above is a program that was compiled & linked using g++. Is there
any other way to initialise a constant member variable using constructor
while creating objects?
There are two points: initialization and constructor body execution, the
reason for const member functions to be initialized in the initializer is
that by the time the constructor body is executed, the initialization is
complete, and for const members, this is not possible because once you
assign the value you can not change it afterwards.

HTH
Jul 4 '08 #2
There are two points: initialization and constructor body execution, the
reason for const member functions to be initialized in the initializer
Of course "const members" not const member functions
Jul 4 '08 #3
On Jul 4, 5:08 am, Anarki <Deepchan...@gm ail.comwrote:
#include <iostream>
using namespace std;

class ConstantMember
{
const int m_const;
public:
ConstantMember( int cons = 10):m_const(con s){}
int getConst() const{ return m_const;}

};

int main()
{
ConstantMember X;//(20);
cout << X.getConst();
return 0;

}

the above is a program that was compiled & linked using g++. Is there
any other way to initialise a constant member variable using
constructor while creating objects?

well yes, copy ctor which is generated for you in the code above and
should look something like ...

class C
{
const int m;
public:
C(int n = 10) : m(n) { }
C(const C& copy) : m(copy.m) // ... this
{
std::cout << "copy\n";
}
int get() const { return m; }
};

int main()
{
C c;
std::cout << c.get() << std::endl;
C cop(c);
std::cout << cop.get() << std::endl;
}

/*
10
copy
10
*/
Jul 4 '08 #4
#include <iostream>
using namespace std;

class ConstantMember1
{
const int m_const;
public:
ConstantMember1 (int cons = 20){m_const = cons;}
int getConst() const{ return m_const;}

};

int main()
{
ConstantMember1 Y;
cout << X.getConst();
return 0;

}
Why doesn't this program compile? What is the difference between the
constructor i gave in first post and this ( ConstantMember( ) and
ConstantMember1 () )
Jul 14 '08 #5
On Jul 14, 3:07*pm, Anarki <Deepchan...@gm ail.comwrote:
#include <iostream>
using namespace std;

class ConstantMember1
{
* * * * const int m_const;
* * * * public:
* * * * ConstantMember1 (int cons = 20){m_const = cons;}
* * * * int getConst() const{ return m_const;}

};

int main()
{
* * * * ConstantMember1 Y;
* * * * cout << X.getConst();
* * * * return 0;

}

Why doesn't this program compile? What is the difference between the
constructor i gave in first post and this ( ConstantMember( ) and
ConstantMember1 () )
sorry there is a typing mistake in the above code its Y.getConst();
but i have typed X.getConst();

Guys is there way to edit my post where i have made mistakes like the
above?
Jul 14 '08 #6
Anarki wrote:
#include <iostream>
using namespace std;

class ConstantMember1
{
const int m_const;
public:
ConstantMember1 (int cons = 20){m_const = cons;}
int getConst() const{ return m_const;}

};

int main()
{
ConstantMember1 Y;
cout << X.getConst();
return 0;

}
Why doesn't this program compile?
Too many bugs? Your compiler errors should have been clear enough.

The only way to initialise a const member is with an initialiser list.
What is the difference between the
constructor i gave in first post and this ( ConstantMember( ) and
ConstantMember1 () )
You used an initialiser list.

--
Ian Collins.
Jul 14 '08 #7
Anarki wrote:
>
Guys is there way to edit my post where i have made mistakes like the
above?
No. Cut and paste code you have tried rather than typing it into the
message.

--
Ian Collins.
Jul 14 '08 #8
On Jul 14, 3:16*pm, Ian Collins <ian-n...@hotmail.co mwrote:
Anarki wrote:
#include <iostream>
using namespace std;
class ConstantMember1
{
* * * * const int m_const;
* * * * public:
* * * * ConstantMember1 (int cons = 20){m_const = cons;}
* * * * int getConst() const{ return m_const;}
};
int main()
{
* * * * ConstantMember1 Y;
* * * * cout << X.getConst();
* * * * return 0;
}
Why doesn't this program compile?

Too many bugs? *Your compiler errors should have been clear enough.
look friend i know the error is due to the constant variable in class.
But why should the compiler raise error? Am looking for more detailed
explanation.
>
The only way to initialise a const member is with an initialiser list.
What is the difference between the
constructor i gave in first post and this ( ConstantMember( ) and
ConstantMember1 () )

You used an initialiser list.
i understand i used initialiser list but whats happening inside the
initialiser list? What does the compiler do when it see the
initialiser list. I think u didn't get what i meant. i explain a bit
more what's the difference between a normal constructor and
constructor that uses initialiser list.
>
--
Ian Collins.
The answer you gave me was just the technical term/terminology of the
example i posted. But what exactly is happening inside this
initialiser list?? Some one please help......
Jul 14 '08 #9
On Jul 14, 10:07*am, Anarki <Deepchan...@gm ail.comwrote:
[snip]
Why doesn't this program compile?
Too many bugs? *Your compiler errors should have been clear enough.

look friend i know the error is due to the constant variable in class.
But why should the compiler raise error? Am looking for more detailed
explanation.
Did you read the post by utab that appeared here 10 days ago?
It's still on Google, so you could find it if you looked.
Socks
Jul 14 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
6524
by: srinivas reddy | last post by:
Hi, Can a constant member function be overloaded with its non-constant equivalent. I mean can void func() be overloaded with void func() const. If so what behaviour is guaranteed, how does the compiler resolve ambiguity?, and how could I call a specific variant? tia, Srinivas
5
4833
by: CoolPint | last post by:
It seems to me that I cannot assign objects of a class which has a constant data member since the data member cannot be changed once the constructor calls are completed. Is this the way it is meant to be? Am I not suppose not to have any constant data member if I am going to have the assignment operator working for the class? Or am I missing something here and there is something I need to learn about? Clear, easy to understand...
8
2863
by: raan | last post by:
Microsoft C++ apparently doesn't permit me to initialize a static constant with in my class scope. Ok, I think that is previously discussed here and people have suggested some hacks to circumvent the issue. That being said, when you try to use that constant as in case expression things get wild. Here is my implementation. /*test.h*/ class test{
3
2111
by: archana | last post by:
Hi all, I have created one sealed class having one constant. Can i access that constant of sealed class without creating object of that class. If yes will internally new object gets created. Or will it behave like static member which remains in memory throughotut applications' lifetime. Please correct me if i am wrong.
3
20878
by: johnmmcparland | last post by:
Hi all, I would like to have a static constant array inside a class definition which would contain the number of days in each month (I am writing a Date class as an exercise). However my attempts so far have been unsuccessful. Take this Test class as an example // test.hpp
9
8895
by: Jess | last post by:
Hello, I was told that if I declare a static class constant like this: class A{ static const int x = 10; }; then the above statement is a declaration rather than a definition. As I've *defined* "x"'s value to be 10, isn't above statement a
6
1688
by: Taras_96 | last post by:
Hi all, Jesse Liberty writes: "Note that the String class provides the operator+. The designer of the Employee class has blocked access to the operator+ being called on Employee objects by declaring that all the string accessors, such as GetFirstName(), return a constant reference. Because operator+ is not (and
4
1330
by: Gordon | last post by:
I'm trying to get a constant from a class, where the constant's name is known, but the class name isn't. I want to do things this way because I want classes to be able to define certain aspects for their setup themselves. For example: I have a situation where I have a script that can deal with objects of one of several classes, but each class needs some slightly different setup parameters. I'm currently taking care of this with a...
7
2813
by: John Koleszar | last post by:
Hi all, I'm porting some code that provides compile-time assertions from one compiler to another and ran across what I believe to be compliant code that won't compile using the new compiler. Not naming names here to remove bias - I'm trying to tell if I'm relying on implementation defined behavior or if this is a bug in the new compiler. Consider this stripped down example:
7
4268
by: Hendrik Schober | last post by:
Hi, this #include <string> class test { typedef std::string::size_type size_type; static const size_type x = std::string::npos; }; doesn't compile using either VC9 ("expected constant expression") or Comeau Online ("constant value is not known"). If I replace
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
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,...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7410
isladogs
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...
0
6674
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3963
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
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.