473,395 Members | 1,404 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

OO techniques Get/Set functions

179 100+
I've been doing some work in C++ for a few months now, but only just had the requirement to design and implement some new classes. I didn't think that would be a problem, however I think I'm taking an incorrect approach for implementing classes, and was wondering if anyone could help me?

My problem, the value I return is not the same as the value I set. Not surprisingly the memory address that the value gets assigned to, doesn't match the one I'm getting the value back from either...

Expand|Select|Wrap|Line Numbers
  1. #include "Entity.h"
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. int main(const int &)
  7. {
  8.     Entity m;
  9.     m.Location().XY(2,15);
  10.     cout << m.Location().Y();
  11.  
  12.     return 0;
  13. }
Entity.h
Expand|Select|Wrap|Line Numbers
  1. #include "Location.h"
  2.  
  3. class Entity
  4. {
  5. private:
  6.    GeoLocation mLocation;
  7. public:
  8.     GeoLocation Location();
  9.     void Location(GeoLocation loc);
  10. };
Entity.cpp
Expand|Select|Wrap|Line Numbers
  1. GeoLocation Entity::Location()
  2. {
  3.     return mLocation;
  4. }
  5.  
  6. void Entity::Location(GeoLocation location)
  7. {
  8.     mLocation = location;
  9. }
GeoLocation.cpp
Expand|Select|Wrap|Line Numbers
  1. class GeoLocation
  2. {
  3. private:
  4.     float mX;
  5.     float mY;
  6.  
  7. public:
  8.     GeoLocation()
  9.     {
  10.         mX = 0.0f;
  11.         mY = 0.0f;
  12.     }
  13.     void X(float x) 
  14.     { 
  15.         mX = x; 
  16.     }
  17.     void Y(float y) 
  18.     { 
  19.         mY = y; 
  20.     }
  21.     void XY(int x, int y)
  22.     {
  23.         mX = (float)x; 
  24.         mY = (float)y; 
  25.     }
  26. };
Output:
0

Any help would be much appreciated. I'm sure it will be something simple, I'm just not quite sure what it is. Thanks.

Ian
Apr 15 '08 #1
8 2046
To Generate Correct output Replace Your Code within main function from following code.

Entity m;
GeoLocation gl;
m.Location(gl.XY(2,15));
GeoLocation glt=m.Location();
cout<<gtl.Y()<<endl;
return 0;

Bye..Take Care..Enjoy Coding
Apr 15 '08 #2
weaknessforcats
9,208 Expert Mod 8TB
Your GeoLocation class has no methods that return data. There are only methods to set the data. That means this code:

cout << m.Location().Y();
won't compile. You can't cout the void of GeoLocation::Y.
Apr 15 '08 #3
TamusJRoyce
110 100+
I may be wrong. Your code may work without the copy constructor and stuff I added. It's good practice to always have a copy constructor, and something to learn.

I'm assuming this is one of the things you would like learn how to implement. Reply back if just a problem with trying to cout a void return type. And what compiler let you compile the cout << m.Location().Y(); ?


Expand|Select|Wrap|Line Numbers
  1. #include "Entity.h"
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. int main(const int &)
  7. {
  8.     Entity m;
  9.     m.Location().XY(2,15);
  10.     //cout << m.Location().Y();
  11. [i]
  12.    // From the int getY() const; method you can
  13.    //   learn from.
  14.    cout << m.Location().getY(); 
  15. [i]
  16.     return 0;
  17. }
Entity.h
Expand|Select|Wrap|Line Numbers
  1. #include "Location.h"
  2.  
  3. class Entity
  4. {
  5. private:
  6.    GeoLocation mLocation;
  7. public:
  8.     // The "&" means pass by reference.  This means that
  9.     //   You are passing the object instead of copying to
  10.     //   another GeoLocation object and passing that.
  11.     // If it gets copied to another GeoLocation object
  12.     //   then passed, it calls the copy constructor, which
  13.     //   you don't have.  so the default constructor is called.
  14.     //   Then a new GeoLocation was returned with only
  15.     //    the default constructors called.  
  16.     GeoLocation &Location(); 
  17.     // This makes program faster with less usage of memory
  18.     //    because when passed by "&" does not require a copy
  19.     //    constructor (GeoLocation x = (GeoLocation)y).  
  20.     void Location(const GeoLocation &loc);
  21. };
Entity.cpp
Expand|Select|Wrap|Line Numbers
  1. GeoLocation Entity::Location()
  2. {
  3.     return mLocation;
  4. }
  5.  
  6. // Parameter here needed changed as well...
  7. void Entity::Location(const GeoLocation &location)
  8. {
  9.     mLocation = location;
  10. }
GeoLocation.cpp
Expand|Select|Wrap|Line Numbers
  1. class GeoLocation
  2. {
  3. private:
  4.     float mX;
  5.     float mY;
  6.  
  7. public:
  8.     GeoLocation()
  9.     {
  10.         mX = 0.0f;
  11.         mY = 0.0f;
  12.     }
  13.  
  14.     // Copy constructor.  Tells how it is suppose to
  15.     //   be copied.  GeoLocation x = (GeoLocation)y;
  16.     //   causes it to be used.  
  17.     GeoLocation(const GeoLocation &loc)
  18.     {
  19.         // Makes sure that:  GeoLocation x;  x = x;
  20.         //   Does not happen.  Just prevents extra work.
  21.         if (&loc != this) 
  22.         {
  23.             mX = loc.getX();
  24.             mY = loc.getY();
  25.         } // End if
  26.     }
  27.     // Must have for copy constructor.  const so that
  28.     //   copy constructor can access.  getX does not
  29.     //   change mX or mY or anything, so valid use of const
  30.     float getX() const 
  31.     {
  32.         return(mX);
  33.     }
  34.     float getY() const
  35.     {
  36.         return(mY);
  37.     }
  38.     void X(float x) 
  39.     { 
  40.         mX = x; 
  41.     }
  42.     void Y(float y) 
  43.     { 
  44.         mY = y; 
  45.     }
  46.     void XY(int x, int y)
  47.     {
  48.         mX = (float)x; 
  49.         mY = (float)y; 
  50.     }
  51. };
Changing GeoLocation Location();
to GeoLocation &Location(); should fix your problem alone.
This prevents a new object being returned, and passes the one returned instead.

Sort of like:
GeoLocation &Location()
{
Geolocation ret;

// Now that there is a copy constructor, this will work...
// But since there wasn't one, here's how it worked:
ret = mLocation; // No copy constructor, so ret simply
// initialized to mX = mY = 0;
return ret;
} // End Location() Function

This is how your function Location was working before. If copy constructors are a bit advanced for you, leave them out for now. Stick with returning references --ClassName &function()-- and having [const ClassName &var] parameters.

// As an example... basic data types such as int, float,
// double, long don't need to be passed or returned by
// reference... (they fit in one register in the processor).
ClassName1 &foofunction(const ClassName2 &var);

Also, look up how to do const functions. getX() I wrote is a good example. int getX() const; has const after it so that if an object gets passed into var through foofunction's (above) parameter, you can access it. var.getX() valid. var.X(5) invalid (because X changes data in GeoLocation, and therefore cannot be a const function).

Apply this to each function which takes in or returns a Class Object, respectively. Experiment by removing const in all functions. It will still work. But many times there are circumstances where something that uses your Class will be const, like text "hello", which is a const char * being passed to your constructor.

Keep programming. It's hard to get the fundamentals of c++, but once you do, the power of what you make is pushed speeds most other languages can't touch (assembly is an exception, but it's harder than c++)

(Sorry if I'm bad at explaining things. I love programming, but am not the best at explaining myself)
Apr 15 '08 #4
oler1s
671 Expert 512MB
You know what I find interesting? The choice to take a bunch of variables, make them private, then create a set of functions that allow you to do nothing more than either access them or assign to them. While you can continue doing this as a syntactical exercise, doing so under the cover of good design is rather dubious.
Apr 15 '08 #5
IanWright
179 100+
Thanks for all the responses,

There is no compiler error, that is my fault for pasting the incorrect section of code. There is indeed a method for returning the Y value that I'm trying to use, so apologies for that...

TamusJRoyce, thats very useful and informative. I'll try and take a look into this in more depth so I understand exactly whats going on. Unfortunately having worked mostly in managed programming languages all the passing member classes by reference is a little new.

oler1s, you'd recommend just having variables defined just in the public scope I'm assuming?

Ian
Apr 16 '08 #6
oler1s
671 Expert 512MB
oler1s, you'd recommend just having variables defined just in the public scope I'm assuming?
I recommend achieving a sensible design. If you define a number of variables privately, the idea is you want to encapsulate them. Writing functions that do nothing but allow you to read them or set them breaks encapsulation. Which then brings up the question, why even bother declaring the variables private in the first place.
Apr 16 '08 #7
TamusJRoyce
110 100+
I recommend achieving a sensible design. If you define a number of variables privately, the idea is you want to encapsulate them. Writing functions that do nothing but allow you to read them or set them breaks encapsulation. Which then brings up the question, why even bother declaring the variables private in the first place.
I foremost agree with oler1s. It's an excellent point, and I do this sometimes habitually when I program. struct (same as class, except it's defaulty public instead of private) and no functions (none needed to get/set/construct) would really solve your problem with your second class.

However if you are just practicing using Inquirers and Manipulators, this is a good example. Having public Inquirers and protected Manipulators (unlike what I've done in my example) allows for other programmers who wish to use your well documented code to change things by making that class their own (through inheritance) can.

It does depend on your purpose and if you plan on either sharing or having others directly use your code.

It's not that I'm implying that you shouldn't make variables public in classes, because it's ok to. Personally, my preference is to hold variables that are similar and I want to be public in a struct.

struct bobsData {
int x, y;
};

And then add an object of that type directly into being public, so users have an idea what data they are manipulating and things are more organized.

But that's me. Coding depends on you and your project. And struct is just a glorified class that starts off as public. Otherwise the keywords are interchangeable (I believe. Research to be sure : )...

Keep learning and programming.

PS. I have been coding for quite a while (12-13 years & I'm 25 & 3 days), so my coding style has become somewhat hard headed. Keep your code unique to your style. It's handy when someone plagiarizes you... : )
Apr 17 '08 #8
Laharl
849 Expert 512MB
Structs can have member functions in C++. The only difference between structs and classes is the default access: public for structs, private for classes.
Apr 17 '08 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

9
by: Tzu-Chien Chiu | last post by:
Hi, "What methods do you ever use to optimize the programs?" We're developing a graphics chip emulator in C++, but it's very slow for big scenes. Even though this is a cross-platform software,...
25
by: JW | last post by:
I'm putting together a bulletin board system for a community that allows folks to put up for sale postings, notices, etc. These notices usually include the posters' email addresses. A similar...
15
by: christopher diggins | last post by:
I have written an article on how to do Aspect Oriented Programming in vanilla C++ (i.e. without language extensions or other tools such as AspectC++). The article is available at...
17
by: EC-AKD | last post by:
Hi All, I am new to the concept of optimising codes in C. I was wondering if C level inlining of code is any way comparable to macros. I believe that inlining is equivalent to writing macros....
2
by: Martin | last post by:
I already know some techniques for writing small footprint software, but now I need to really squeeze the software I'm writing into a small space (embedded software). Is there a good web page...
11
by: Mellow Crow | last post by:
I had a problem in IE 6 when trying to insert a table using W3C DOM techniques. I found a solution and share it. :) Initially I had...... ********************** <!DOCTYPE html PUBLIC...
19
by: JoeC | last post by:
I have seen many books that teack coding for C++. What are ways to improve my techniques for writing larger programs. I have written many demo programs learning some aspects of code wether it be...
16
by: Panos Laganakos | last post by:
I've been thinking if there's a point in applying some specific OOP techniques in Python as we do in other languages. i.e. we usually define private properties and provide public functions to...
5
by: Jon Rea | last post by:
I work with molecular simulations. In a normal infinate space simulation, a particle can occupy any cartesian position in space. If i want the distance between two particles in a system I can...
0
by: Matthew Fitzgibbons | last post by:
I'm by no means a testing expert, but I'll take a crack at it. Casey McGinty wrote: I've never run into this. Rule of thumb: always separate software from hardware. Write mock classes or...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.