473,657 Members | 2,595 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iterate through member variables of a class

bst
Is there a way to iterate through member variables of different names, of
course, one by one from the very first one in a while loop, for example?
Thanks!
Jul 22 '05 #1
10 8739
"bst" <bs***@import.c om> wrote...
Is there a way to iterate through member variables of different names, of
course, one by one from the very first one in a while loop, for example?


No.
Jul 22 '05 #2
"bst" <bs***@import.c om> wrote in message
news:9W******** *************@b gtnsc04-news.ops.worldn et.att.net...
Is there a way to iterate through member variables of different names, of
course, one by one from the very first one in a while loop, for example?
Thanks!


I'm probably doing something stupid, but did you mean something like this?
Even if something's wrong with it (and there probably is), at least I'll
learn something when everyone corrects me :)

One thing I do know that's wrong is the public member variables in both
classes, but I left those in so that I could fool around with it (and I
can't think of any other way to make this setup work).

Provided they work, the classes could be altered to be templates instead.

#include <iostream>

using std::cout;

class ReadMe {

public:

ReadMe(int num1, int num2, int num3, int num4) {

var1 = num1;

var2 = num2;

var3 = num3;

var4 = num4;

}

int var1;

int var2;

int var3;

int var4;

};

class Reader {

public:

Reader(ReadMe& readFromThis) : target(readFrom This) { }

void printTargetVars () const;

ReadMe& target;

};

void Reader::printTa rgetVars() const {

int* arr[4] = { &target.var1 , &target.var2 , &target.var3 , &target.var4 };

int i = 0;

while(i < 4) {

cout << *arr[i] << "\n";

++i;

}

}

int main() {

ReadMe readThisOne(1,2 ,3,4);

ReadMe readThisTwo(5,6 ,7,8);

Reader reader1(readThi sOne);

Reader reader2(readThi sTwo);

reader1.printTa rgetVars();

reader2.printTa rgetVars();

return 0;

}

//mike tyndall
Jul 22 '05 #3
"Stephen Tyndall" <sw*******@hotm ail.com> wrote in message
news:Hv******** ************@co mcast.com...
"bst" <bs***@import.c om> wrote in message
news:9W******** *************@b gtnsc04-news.ops.worldn et.att.net...
Is there a way to iterate through member variables of different names, of course, one by one from the very first one in a while loop, for example?
Thanks!
I'm probably doing something stupid, but did you mean something like this?
Even if something's wrong with it (and there probably is), at least I'll
learn something when everyone corrects me :)

One thing I do know that's wrong is the public member variables in both
classes, but I left those in so that I could fool around with it (and I
can't think of any other way to make this setup work).

[snip] class Reader {

public:

Reader(ReadMe& readFromThis) : target(readFrom This) { }

void printTargetVars () const;

ReadMe& target;

};

void Reader::printTa rgetVars() const {

int* arr[4] = { &target.var1 , &target.var2 , &target.var3 , &target.var4 };

int i = 0;

while(i < 4) {

cout << *arr[i] << "\n";

++i;

}

[snip]

Looks OK to me, except for the public members and a few minor tweaks that
could be made. Another option is to forego individual members and just use
an array from the start.

--
David Hilsee
Jul 22 '05 #4
"David Hilsee" <da************ *@yahoo.com> wrote in message
Looks OK to me, except for the public members and a few minor tweaks that
could be made. Another option is to forego individual members and just use an array from the start.


How about a map? As in <string variable_name, int variable_value> .
Jul 22 '05 #5
"David Hilsee" <da************ *@yahoo.com> wrote in message
news:Oc******** ************@co mcast.com...
"Stephen Tyndall" <sw*******@hotm ail.com> wrote in message
news:Hv******** ************@co mcast.com... [code snipped] Looks OK to me, except for the public members and a few minor tweaks that
could be made.
If you have the time, could you tell me what tweaks? I'm kind of a beginner
(2 months or so of programming now), and I'm trying to teach myself good
programming habits.
Another option is to forego individual members and just use
an array from the start.


Huh. I didn't even think of that. Guess I've learned something then :)

//mike tyndall
Jul 22 '05 #6
"Siemel Naran" <Si*********@RE MOVE.att.net> wrote in message
news:6Q******** *************@b gtnsc04-news.ops.worldn et.att.net...
"David Hilsee" <da************ *@yahoo.com> wrote in message
Looks OK to me, except for the public members and a few minor tweaks that could be made. Another option is to forego individual members and just
use an array from the start.


How about a map? As in <string variable_name, int variable_value> .


I haven't learned maps yet, so I'll have to look into them. Thanks for the
tip!

//mike tyndall
Jul 22 '05 #7
"Stephen Tyndall" <sw*******@hotm ail.com> wrote in message
news:yv******** ************@co mcast.com...
"David Hilsee" <da************ *@yahoo.com> wrote in message
news:Oc******** ************@co mcast.com...
"Stephen Tyndall" <sw*******@hotm ail.com> wrote in message
news:Hv******** ************@co mcast.com... [code snipped]
Looks OK to me, except for the public members and a few minor tweaks that could be made.


If you have the time, could you tell me what tweaks? I'm kind of a

beginner (2 months or so of programming now), and I'm trying to teach myself good
programming habits.


It's nothing, really. One point was that you used a while when a for would
have been more natural. The other point was that you could have used the
sizeof() "trick" to avoid using the literal 4 in your code.

int* arr[] = { &target.var1 , &target.var2 , &target.var3 , &target.var4 };
int numElems = sizeof(arr) / sizeof(arr[0]);

for ( int i = 0; i < numElems; ++i ) {
cout << *arr[i] << "\n";
}

Thanks to sizeof(), you can add or remove elements from the array and the
other code doesn't have to change. It comes in handy more often in C than
it does in C++, because in C code it is more likely to have an array whose
size can be determined by the compiler. I don't know if you've seen that
before or not, so there it is. Like I said, minor tweaks. To be completely
anal, the int is being used to iterate over an array whose length is defined
in terms of std::size_t, but that's far too picky for my tastes.

--
David Hilsee
Jul 22 '05 #8
"David Hilsee" <da************ *@yahoo.com> wrote in message
news:UY******** ************@co mcast.com...
"Stephen Tyndall" <sw*******@hotm ail.com> wrote in message
news:yv******** ************@co mcast.com...
"David Hilsee" <da************ *@yahoo.com> wrote in message
news:Oc******** ************@co mcast.com...
"Stephen Tyndall" <sw*******@hotm ail.com> wrote in message
news:Hv******** ************@co mcast.com... [code snipped]
Looks OK to me, except for the public members and a few minor tweaks
that could be made.

Just a note: I didn't realize that the Reader class' ReadMe& didn't need to
be public. That's fixed now; I also rewrote both classes as templates and
added a new template class that can read two ReadMe's of differing types
(yes, I'm still messing with it).

If you have the time, could you tell me what tweaks? I'm kind of a
beginner (2 months or so of programming now), and I'm trying to teach
myself good programming habits.


It's nothing, really. One point was that you used a while when a for

would have been more natural.
I did that because the OP was asking about iterating through member
variables of a class by using a while loop. I generally prefer for loops.
The other point was that you could have used the
sizeof() "trick" to avoid using the literal 4 in your code.

int* arr[] = { &target.var1 , &target.var2 , &target.var3 , &target.var4 };
int numElems = sizeof(arr) / sizeof(arr[0]);

for ( int i = 0; i < numElems; ++i ) {
cout << *arr[i] << "\n";
}

Thanks to sizeof(), you can add or remove elements from the array and the
other code doesn't have to change. It comes in handy more often in C than
it does in C++, because in C code it is more likely to have an array whose
size can be determined by the compiler. I don't know if you've seen that
before or not, so there it is. Like I said, minor tweaks.
I didn't know this one. That's pretty clever (to me, anyway)!
To be completely
anal, the int is being used to iterate over an array whose length is defined in terms of std::size_t, but that's far too picky for my tastes.


So it would be better if I declared the int as a size_t instead? Or does it
matter? Thanks for your time.

//mike tyndall, finally posting as myself
Jul 22 '05 #9
"Mike Tyndall" <sw*******@hotm ail.com> wrote in message
news:Pr******** ************@co mcast.com...
<snip>
So it would be better if I declared the int as a size_t instead? Or does it matter? Thanks for your time.


No, don't bother. It's unsigned, and that opens up a can of worms if you're
not paying attention. Just keep in mind that you may see code that uses
std::size_t instead.

--
David Hilsee
Jul 22 '05 #10

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

Similar topics

7
2106
by: WXS | last post by:
Vote for this idea if you like it here: http://lab.msdn.microsoft.com/productfeedback/viewfeedback.aspx?feedbackid=5fee280d-085e-4fe2-af35-254fbbe96ee9 ----------------------------------------------------------------------------- This is a consortium of ideas from another thread on topic ----------------------------------------------------------------------------- One of the big issues of organizing items within a class, is there are many...
5
29347
by: jaso | last post by:
Hi, If have a structure of a database record like this: struct record { char id; char title; ... }; Is there some way to find out how many member variables there is in the struct and then iterate through them?
1
3158
by: mangalalei | last post by:
A static data member can be of the same class type as that of which it is a member. A nonstatic data member is restricted to being declared as a pointer or a reference to an object of its class. And I haved used the sizeof operator to test a class which has a static data member, the class size is all the nonstatic data member except the static data member. In compiler's view, is the static data member constructed after the whole class...
3
1916
by: toton | last post by:
Hi, I have a container class, and I want to iterate over a portion of the container class while I insert/remove item from it. Noting down the present location & constructing iterator from there is working, however storing a copy of the iterator itself do not work. For example, If I have a vector of int. vector<intv; v.push_back(5); v.push_back(10);
7
2180
by: Valeriu Catina | last post by:
Hi, consider the Shape class from the FAQ: class Shape{ public: Shape(); virtual ~Shape(); virtual void draw() = 0;
15
3837
by: Bob Johnson | last post by:
I have a base class that must have a member variable populated by, and only by, derived classes. It appears that if I declare the variable as "internal protected" then the base class *can* populate the variable, but the population is not *required* by the derived class (which must be the case). What would meet the requirements is if I create an abstract method in the base class that populates the member variable. In this case the...
7
3956
by: Immortal Nephi | last post by:
My project grows large when I put too many member functions into one class. The header file and source code file will have approximately 50,000 lines when one class contains thousand member functions. Is it normal how C++ Compiler can compile large class without any problem? Didn't C++ Compiler have rules to limit the number of member functions? One big object has complex operations how member variables and member functions can be...
13
11449
by: Henri.Chinasque | last post by:
Hi all, I am wondering about thread safety and member variables. If I have such a class: class foo { private float m_floater = 0.0; public void bar(){ m_floater = true; }
17
8367
by: Juha Nieminen | last post by:
As we know, the keyword "inline" is a bit misleading because its meaning has changed in practice. In most modern compilers it has completely lost its meaning of "a hint for the compiler to inline the function if possible" (because if the compiler has the function definition available at an instantiation point, it will estimate whether to inline it or not, and do so if it estimates it would be beneficial, completely regardless of whether...
0
8392
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
8305
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
8823
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8730
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8503
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7321
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...
0
5632
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();...
1
2726
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
1950
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.