0

Please forgive me if I asked too big a question. I tried to work it into an example I found in the forum. Though this is for a class, I'm just trying to figure out my homework and my question is centered around this forum question - I'm not asking for magic code to get an A! (actually am taking this class p/fail for personal enrichment.) .... I have been using the answer to the following question to try to buildup to a better understanding of a homework problem in my C++ class. But I'm getting stuck because there is some basic idea (just one?:-) I think I just don't get. The code I attached to the bottom of this question is me working with this forum sample, but I haven't gotten a sense yet, of how to setup an array that is inside a class. That is part of the assignment.

C++: syntax for accessing member struct from pointer to class

I'm fighting this problem somewhat, because my background is as a structured programmer - the reason I'm taking this class is to work my brain into an oop mode. So sometimes I go off on a track that leads away from oop, without realizing it.

MY QUESTION

I need to be able to instantiate an object of class 'Foo'. That object needs to have an array of 3 kinds of things associated with it. Uh.. I think in this context those things would be called 'Bar'. Those things have attributes 'otherdata' and 'andMoreData'. There is just one piece of data in the object called 'somedata' (Sorry I am mostly using the names of variables from the code I found here).

So I see it like this.

I have an object I instantiated and it is named 'foo' it is of class 'Foo'. It has one ivar called 'somedata' I can assign a value to. Then I want to setup 3 occurances of 'Bar' data. Each of those occurrances will consist of the ivars otherdata and andMoreData. Maybe with default data for each ivar like this otherdata = 1, andMoreData = 2

I can't figure out how I write a constructor to get the defualt data into my object. I can't figure out how I access the data within the object for display or changing.
... I hope I didn't ask too big a question here ....

HERE IS THE CODE I HAVE BEEN TRYING TO REWORK from this forum , hoping that I could build up from this explanation to a good understanding, but I get stuck when I try to create a constructor. ....

/*  MY VARIATION ON FOOBAR
    Original EXamples found at 
https://stackoverflow.com/questions/915106/c-syntax-for-accessing-member-struct-from-pointer-to-class

*/

#include <iostream>
#include <iomanip>
using namespace std;

const int MAX_num = 3;
class Foo{
    // I think I have this right, that Bar is the name of the struct
    //   and 'mybar' is an ivar within the class, with a data type of 'Bar'
    //   
public:
    struct Bar{
        int otherdata;
        int andMoreData;
    } 
    mybar; // I think I am saying that mybar is an ivar of type Bar

    /* Here I tried to move forward with what I wanted to do, but the
     compiler thought it was a bad idea
    */ 
    // Here I'm attempting to create a constructor with default data
     { // set default data for mybar
        otherdata = 1;
        andMoreData = 2;
    }
    // Here I'm attempting to fill an array 'nmybar' with 3 occurances of my struct
    //  but I don't know how to say that it's associated with that struct/variable
    //  actually this seems like the WRONG place to do this, but my teachers example
    //    does something similar in the .h file (and of course his example works fine, but I 
    //  don't understand it

    nmybar[MAX_num];    // this calls mybar() MAX_num times

    int somedata;
};

int main(){

    // I instantiate class Foo and name my object 'foo'

    Foo foo;

    // Then I want to refer to the mybar portion of my foo object
    //   mybar could contain more than one variable itself, in this case
    //      it doesn't. so I am just referring to the one variable that
    //         a 'Bar' variable can contain, which is 'otherdata'
    //  HERE I added a second variable to the struct to make sure I understood how 
    //   to use it , ok that works

    foo.mybar.otherdata = 5;
    foo.mybar.andMoreData = 6;
    cout << foo.mybar.otherdata << endl ;
    cout << foo.mybar.andMoreData << endl ;

    return 0;
}

/*
 Program loaded.
 run
 [Switching to process 1297]
 Running…
 5
 6

 Debugger stopped.
 Program exited with status value:0. */
1
  • If you edit your question to fix up the formatting, you might get responses more quickly. Just select the entire code portion and click on the {} icon above the editor. Commented Mar 24, 2011 at 0:22

4 Answers 4

1

I cleaned up the code a bit and generated an working example.

#include <iostream>
#include <iomanip>

using namespace std;

const int MAX_num = 3;

class Foo
{
public:
   struct Bar {
      int otherdata;
      int andMoreData;

      Bar () : otherdata(1), andMoreData(2) { };
   };

   Bar mybar[MAX_num]; // Array of MAX_num Bar's
   int somedata;
};

int main ()
{
   Foo foo;

   foo.mybar[0].otherdata   = 5; // [0] for first element, [1] for second, [2] for third
   foo.mybar[0].andMoreData = 6; // don't try to access higher positions, as the array has
                                 // only three elements

   cout << foo.mybar[0].otherdata << endl;   // 5
   cout << foo.mybar[0].andMoreData << endl; // 6

   cout << foo.mybar[1].otherdata << endl;   // 1
   cout << foo.mybar[1].andMoreData << endl; // 2

   return 0;
}

But it looks a bit like you don't really know what to do. I suggest you take an c++ tutorial or book (on stackoverflow there are some entries about good beginner-books) to learn c++ from beginning. While it might look more time-consuming at beginning, you will learn much more that way.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to both of you. I'm going to sit and go through these. I know it DOES look like I don't know what I'm doing! I was thinking about deleting the post and starting over with it. I actually have a textbook that I've been really working to use (I even do the questions and check my answers). This particular problem has me stumped because it's not laid out like other problems in the book and went I went to ask the teacher about it, he said, well a struct is just like a data type.
1

You write a constructor for Bar just like you would any constructor. If Bar wasn't inside Foo then it would be something like this:

struct Bar {
    Bar();
    int otherdata;
    int andMoreData;
};

Bar::Bar(): otherdata(1), andMoreData(2) { }

When you put Bar inside of Foo it becomes:

class Foo {
    struct Bar {
        Bar();
        int otherdata;
        int andMoreData;
    };
};

Foo::Bar::Bar(): otherdata(1), andMoreData(2) { }

Then to give every instance of Foo 3 instances of Bar objects you would do something like:

class Foo {
    struct Bar {
        Bar();
        int otherdata;
        int andMoreData;
    };
    Bar bars[3];
};

Foo::Bar::Bar(): otherdata(1), andMoreData(2) { }

There are other ways you could format this, but the above is the most idiomatic. You will note that the bars variable and the Bar class are both private in the above. It is generally recognized that member-variables should be private within a class (I'm telling you this because you said your purpose is to understand OO better.) It is sometimes acceptable to make the structure (Bar) itself publicly available, but if the struct is just for the class' convenience, then it is better to make it private as well.

1 Comment

Thank you for telling the 'most idiomatic' way. Yes, that is what I'm going for here. Trying to do it and get it both.
0
const int MAX_num = 3;
class Foo{
public:
    struct Bar{
        Bar() { // Constructor - initializes a Bar instance
            otherdata = 1;
            andMoreData = 2;
        }
        int otherdata;
        int andMoreData;
    };
    Bar mybar; // Separating the Bar type from the mybar variable. Your original syntax is valid, but this is more common
    Bar nmybar[MAX_num]; // nmybar is an array of MAX_num Bar's
    int somedata;
};

1 Comment

I'm trying to upvote answers and I keep being told to login or register. I AM logged in and when I try to do that, it tells me so.
0

OK, BIG THANKS to people posting I was able to work up a code sample that I understood.

Then I was able to apply the ideas I learned to my class problem.

I am now able to create the kind of class with a struct and an array that I needed! Now I can rework the rest of my homework solution (I got all the bits and pieces for running the machine to work but with only one drink) to accommodate the desired class. Thank you!

Here is my new sample class, with it's real names, etc.

/* C++ syntax/how to declare, fill and access an array within a class started off with MacGucky's solution */

include

include

using namespace std;

const int UNIQUE_DRINKS = 5;

/* class DrinkMachine { private: string drink ; double cost; int drinksLeft; double moneyCollected;

*/

class DrinkMachine { public: /* So there are TWO members in class 'DrinkMachine' one is 'moneyCollected' the other is 'Bottles' 'Bottles' has 3 attributes: a) 'drink' -name of drink b) 'cost' - how much for one drink c) 'drinksLeft' - how many of each unique drink are stocked in the machine */ struct Bottles { string drink; double cost; int drinksLeft;

    // this is a constructor for 'Bottles' It puts default data into an instance OF 'Bar'
    Bottles () : drink("cola"), cost(0.75), drinksLeft(20) { };
};
Bottles myBottles[UNIQUE_DRINKS]; // myBottles is an Array of UNIQUE_DRINKS Bottles
// refer to 'myBottles' like a member, that has children   (two dots for it's children)
//              versus one dot for moneyCollected

double moneyCollected;

};

int main () { // instantiate DrinkMachine, create an object named 'Building1'

cout << "Lets's fill up the drink machine in Building 1 ! " << endl ;
DrinkMachine Building1;
Building1.moneyCollected = 20.00;

// objectname.ARRAYNAME[position].ivarWithinStruct

// KEEP ALL the defaults for first Bottles item (Cola)
// most of the rest matches the defaults except name and price on water

    Building1.myBottles[1].drink   = "grape soda"; 
    Building1.myBottles[2].drink   = "root bear"; 
    Building1.myBottles[3].drink   = "orange soda"; 
    Building1.myBottles[4].drink   = "bottled water"; 
    Building1.myBottles[4].cost    = 1.00; 

for (int i=1; i<=4;i++) {
    cout << Building1.myBottles[i].drink  ;    
    cout << " " ;
    cout << Building1.myBottles[i].cost  ;   
        cout << " " ;
    cout << Building1.myBottles[i].drinksLeft ;   //  
    cout << endl;
}
cout << "\t * * * " << endl ;
cout << "\t Total Bucks Collected Today " << Building1.moneyCollected << endl ;
return 0;

}

/* Loading program into debugger… Program loaded. run [Switching to process 3332] Running… Lets's fill up the drink machine in Building 1 ! grape soda 0.75 20 root bear 0.75 20 orange soda 0.75 20 bottled water 1 20


Total Bucks Collected Today 20

Debugger stopped. Program exited with status value:0. */

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.