Thread: For-loop to assign values to objects in array [BEGINNER]

  1. #1
    Registered User
    Join Date
    Jun 2020
    Posts
    3

    Question For-loop to assign values to objects in array [BEGINNER]

    Hello,

    This is my first time using this forum, and I'm very new to programming in C++. Please forgive any misuse of terminology, and feel free to correct me on my verbiage mishaps, as I appreciate anything that I can learn from.

    I've just learned about stack and heap, and I'm fairly adequate with basic for-loops, arrays, and somewhat sufficient with pointers.

    My task is to create a primitive array of objects belonging to my 'Planet' class that is not shown here. I am to allocate memory for 26 objects in the array as shown in this line:

    Planet *pArray = new Planet[26];

    and name each element in pArray by the corresponding letter in the alphabet... [0] = A, and so on...

    I figured the best way I could do this was to use a char array and a for loop, as seen in the entire snippet of code below:

    Code:
    char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVQXYZ";
    
    
    int nChar = sizeof(alpha)-1;      // equals 26
    
    
    Planet *pArray = new Planet[nChar];  // array initialization
    
    
    for (int p = 0; p<=nChar; p++) {     // loop 26 times
    
            *pArray[p] = alpha[p];            // error line
    
    }

    I am getting error on the last line there:

    error: no match for 'operator*' (operand type is 'Planet')

    I am usually decent at figuring errors our, but I'm stumped on this one. I tried removing the asterisk on *pArray in the for-loop, although I believe it's needed. It errors either way! Please help me.

    The main point of the practice is that I leave the object array alone, as that was how it was taught in the lesson to be done. The rest of it was my own and fine to change.

    My apologies if I left anything out that I shouldn't have. I am a certified noob. Let me know about it and I'll include it.

    Thank you
    for taking the time to read this, and more so if you're able to help!
    Last edited by Mr. I Need Help; 06-17-2020 at 01:04 PM.

  2. #2
    Registered User
    Join Date
    Dec 2017
    Posts
    971
    In the future, remember that it is best to post a complete program (headers,main,etc) so that we can easily run (or try to compile) it.

    The compiler does not know how to set a Planet to a char. If you want to be able to assign a char to a Planet then you need to define an operator= overload for that purpose.

    Alternatively if the char that Planet stores is public then you can directly assign to it:
    Code:
        planets[p].ch  = alpha[p];
    Here's the operator= overload (and an operator<< overload for output).
    Code:
    #include <iostream>
    using namespace std;
     
    class Planet {
        char ch;
     
    public:
        Planet() : ch(0) {}
     
        Planet& operator=(char c) { ch = c; return *this; }
     
        friend ostream& operator<<(ostream& out, const Planet& p) {
            return out << p.ch;
        }
    };
     
    int main() {
     
        char alpha[] = "ABCDEFGHIJKLMNOPQRSTUVQXYZ";
        int nPlanets = sizeof(alpha) - 1;
     
        Planet *planets = new Planet[nPlanets];
     
        for (int p = 0; p < nPlanets; p++)
            planets[p] = alpha[p];
     
        for (int p = 0; p < nPlanets; p++)
            cout << planets[p] << '\n';
     
        delete[] planets;
    }
    Last edited by john.c; 06-17-2020 at 01:56 PM.
    If you want the truth to stand clear before you, never be for or against. - Sent-ts'an

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    38,204
    > My task is to create a primitive array of objects belonging to my 'Planet' class that is not shown here.
    Well without it, it's impossible to say what could possibly make sense of your assignment.

    Does this make sense to you?
    Planet mars = 'M';

    Because that's what you're trying to do.

    Oh, and your loop iterates 27 times (and falls of the ends of your allocated space).

    Code:
    for (int p = 0; p<nChar; p++) {     // loop 26 times
            pArray[p] = alpha[p];            // error line
    }
    If there is something meaningful to be done with the assignment.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Jun 2020
    Posts
    3
    Thank you both for the help! I'll post correctly next time, sorry for making you type the rest out.

    Salem, thank you for pointing out my incorrect operator there!
    Last edited by Mr. I Need Help; 06-17-2020 at 02:48 PM.

  5. #5
    Registered User
    Join Date
    Jun 2020
    Posts
    3
    In case either of you care about my remedial level code, here is the finished script. After much searching and reviewing past lessons, it works. For readability's sake, I stripped all code unrelated to the essential Planet class, and the aforementioned task in main function. Once I had it working, I polished it up with toupper() function which I just learned about as well.

    Embarrassingly, I had that setName method in Planet class already coded in the entire time, and I did not even think to invoke it. Salem, I now see what you meant with your your Mars statement. Huge oof...

    Code:
    #include <iostream>
    using namespace std;
    
    class Planet {
    private:
        string name;
    
    public:
        Planet() {
            this->name = "Unnamed";
        }
        ;
        void setName(string name) {
            cout << "Planet name changed to '" << name << "'." << endl;
            this->name = name;
        }
        ;
    
    };
    
    int main() {
    
        Planet *planets = new Planet[26];
    
        char c = toupper('a');
    
        for (int p = 0; p < 26; p++, c++) {
            string n(1, c);
            planets[p].setName(n);
    
        }
    
        return 0;
    }
    Last edited by Mr. I Need Help; 06-17-2020 at 04:37 PM.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,001
    That's a good attempt, but instead of using new[], you should use a std::vector. For example:
    Code:
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    class Planet {
    public:
        explicit Planet(const std::string& new_name = "Unnamed") : name(new_name) {
            cout << "Planet initialised with the name of '" << name << "'." << endl;
        }
    
        void setName(const std::string& name) {
            cout << "Planet name changed to '" << name << "'." << endl;
            this->name = name;
        }
    
        // ...
    private:
        string name;
    };
    
    int main() {
        vector<Planet> planets;
        planets.reserve('Z' - 'A' + 1);
    
        for (int c = 'A'; c <= 'Z'; ++c) {
            planets.emplace_back(string(1, c));
        }
    
        // ...
    
        return 0;
    }
    Compared to your version, this:
    • Makes use of the constructor to initialise the Planet with the name that you want, and if no name is provided, it defaults to "Unnamed" like your version, except that it does initialisation instead of assignment.
    • Changes the parameter type of setName to a const reference because conceptually you want to copy the string once, not twice.
    • Has no worries related to manual memory management: in your version, you should delete[] what you new[], and then you need to worry about exceptions being thrown or propagated in between.
    • More efficiently constructs the vector of Planets by populating it with the Planet objects initialised to their desired name, rather than default constructing them and then assigning them with their desired names.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How do I assign values to elements of a 2D array?
    By Karyumi in forum C Programming
    Replies: 9
    Last Post: 06-21-2012, 02:48 PM
  2. Assign values to array of structures
    By rlesko in forum C++ Programming
    Replies: 8
    Last Post: 12-12-2010, 03:31 PM
  3. Assign values to a set of array of structures
    By glucosonte in forum C Programming
    Replies: 1
    Last Post: 08-26-2009, 08:10 AM
  4. Assign an arrays values to another array
    By laczfinador in forum C Programming
    Replies: 3
    Last Post: 05-06-2009, 07:46 AM
  5. 3-d array assign string values
    By WaterNut in forum C++ Programming
    Replies: 8
    Last Post: 07-01-2004, 12:02 AM

Tags for this Thread