Solved

20. Can a constant method be called for object-variables? What about usual method - for a constant object?

Posted on 2015-01-24
19
57 Views
Last Modified: 2015-02-15
Can a constant method be called for object-variables? What about usual method - for a constant object?
0
Comment
Question by:Nusrat Nuriyev
  • 9
  • 8
  • 2
19 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 40568228
As a rule of thumb, if you have a constant object, you are only allowed to call 'const' mthods, anything else would defy the purpose of a const object. You can also read all public data, but not write it.
0
 
LVL 32

Expert Comment

by:phoffric
ID: 40568732
I didn't understand your question.
Does http://www.experts-exchange.com/Programming/Languages/CPP/Q_28603149.html address them?
0
 

Author Comment

by:Nusrat Nuriyev
ID: 40584103
jkr, could you please show some examples for both cases?
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 500 total points
ID: 40584126
Sure, e.g.

class MyClass {
public:
  MyClass() : A(42), B(0) {}
  int A;
  void SetB(int val) { B = val;}
  const int GetB() const { return B;}
protected:
  int B;
};

int main () {

  const MyClass mc1;
  MyClass mc2;

  int test1 = mc1.GetB(); // OK

  int test2 = mc1.A; // OK

  int test3 = mc2.A; // OK

  mc2.A = 0; // OK

  mc2.SetB(16); // OK

  mc1.SetB(23); // compiler error - calling non-const method on a const object

  return 0;
}

Open in new window

0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 500 total points
ID: 40584162
Ooops, forgot one like:

  mc1.A = 42; // compiler error - can't assign a value to a const object

Open in new window

0
 

Author Comment

by:Nusrat Nuriyev
ID: 40604591
const int GetB() const { return B;}

What does mean both of this const's?

1.  as I know the second const is responsible for constness of whole object. the state of object? right?
But what about first const, at return value?
0
 
LVL 86

Expert Comment

by:jkr
ID: 40604610
Yes, it means that it returns a const value. Let me illustrate it like that:

const /* indicates a const return value */ int GetB() const /* means that this method doesn not alter the object it belongs to */ { return B;}

Open in new window


Declaring a const method to have a non-const return value usually does not make a lot of sense, only e.g. for numeric values that you use to initialize something else.
0
 

Author Comment

by:Nusrat Nuriyev
ID: 40604615
I got this part. But?

const int x = 5;

But does it make sense to return something to the x?
like this?
x = mc1.GetB();
does it make sense?
0
 

Author Comment

by:Nusrat Nuriyev
ID: 40604621
I have changed to this
int GetB() const { return B;}

Open in new window


but still do not get what is the affect of const for this code
int test1 = mc1.GetB(); // OK

Open in new window

or maybe it affects to other code?
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 40604628
It affects the way the compiler can optimize the code. And I have to admit that it does not seem to make a lot of sense for POD types (POD as 'Plain Old Data'), that concept really gets interesting and powerful when it comes to return more complex data that is encapsuled in the class. Think of e.g. a lookup table.
0
 

Author Comment

by:Nusrat Nuriyev
ID: 40604659
For example , this seems to be a look up table, which is just an array , but with  integer constants
static const unsigned short MortonTable256[256] = 
{
  0x0000, 0x0001, 0x0004, 0x0005, 0x0010, 0x0011, 0x0014, 0x0015, 
  0x0040, 0x0041, 0x0044, 0x0045, 0x0050, 0x0051, 0x0054, 0x0055, 
  0x0100, 0x0101, 0x0104, 0x0105, 0x0110, 0x0111, 0x0114, 0x0115, 
  ... 32 lines in total ...
  0x5540, 0x5541, 0x5544, 0x5545, 0x5550, 0x5551, 0x5554, 0x5555
};

Open in new window


Do I understand look-up table right?
Why it's powerfull to use const in lookup? Example, please.
0
 
LVL 86

Expert Comment

by:jkr
ID: 40604669
Well, 'powerful' might be the wrong word here. Its cleaner. You would not want any other code to be able to modify the table, would you?
0
 

Author Comment

by:Nusrat Nuriyev
ID: 40604675
Okay :)

that concept really gets interesting and powerful when it comes to return more complex data that is encapsuled in the class.
When you say this, did you mean the const keyword in general rather than absense/presence of const keyword in this code, right?

int GetB() const { return B;}

Open in new window

0
 
LVL 86

Expert Comment

by:jkr
ID: 40604951
Interestingly enough in both ways ;o)

Let's try that one:

class CombustionEngineLinkup{
public:

  const unsigned int GetRPM() const { return RPM;}

private:

  unsigned int RPM;
};

class SpeedoMeter() {
public:
  const unsigned int GetCurrentRPM() const {return eng.GetRPM();

protected:
  CombustionEngineLinkup eng;
}

Open in new window

0
 

Author Comment

by:Nusrat Nuriyev
ID: 40611276
stackoverflow.com/questions/8716330/purpose-of-returning-by-const-value
I have written an example, as I understand constness have something with lvalue

class Dollars
{
    private:
        int m_nDollars;
    public:
        Dollars(int nDollars) { m_nDollars = nDollars; }
        friend const Dollars operator+ (const Dollars &d1, const Dollars &d2);
        int GetDollars() { return m_nDollars; }
};

const Dollars operator+ (const Dollars &d1, const Dollars &d2)
{
    return Dollars(d1.m_nDollars + d2.m_nDollars);
}

int main()
{
    Dollars d1(12);
    Dollars d2(8);

    std::cout << "I'm gonna pop some tags" << std::endl
              << "Only got " << (d1 + d2).GetDollars() << " dollars in my pocket" << std::endl
              << "I, I, I'm hunting, lookin' for a come-up" << std::endl
              << "This is fucking awesome." << std::endl;
    return 0;
}

Open in new window



This example will work without const  at return of operator+.
Also I have understand that I could write like this:
operator+(d1,d2).GetDollars()

Open in new window

Now, I understand your words about that  overloading operator does not belong to the class, do you remember, we had such example? :)
0
 
LVL 86

Expert Comment

by:jkr
ID: 40611296
Yes, I do remember - and sometimes it's hard to come up with an example for stuff that you work with and have taken for granted over decades ;o)

Just as a side note: As for EE rules, *I* would not be allowed to linkt to SO, since it is considered a competing site...
0
 

Author Comment

by:Nusrat Nuriyev
ID: 40611329
:)

>>> Just as a side note: As for EE rules, *I* would not be allowed to linkt to SO, since it is considered a competing site...
Ah, just I forgot that :)
0
 
LVL 86

Expert Comment

by:jkr
ID: 40611354
Well, you as someone asking a question are allowed if I am not mistaken...
0
 
LVL 32

Expert Comment

by:phoffric
ID: 40611623
>> "overloading operator does not belong to the class"

As I just happened to see this remark and not knowing its context, I just wanted to make sure we are all on the same page. Namely that overloading operator can belong to the class, but doesn't have to. Ok?

The following set of operators is commonly overloaded for user-defined classes:
    •= (assignment operator)
    •+ - * (binary arithmetic operators)
    •+= -= *= (compound assignment operators)
    •== != (comparison operators)
http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now