Return Object in Function (C++) [syntax?]

  • (2 Pages)
  • +
  • 1
  • 2

26 Replies - 1048 Views - Last Post: 17 July 2012 - 12:46 PM Rate Topic: -----

#1 lobsterEater  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 24
  • Joined: 15-July 12

Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 11:35 AM

Hello, good people of the dream in code site. :D
I'm having a little difficulties with my program.
I'm trying to create a function "Star generateStars(int, int, string)" that generates Stars for my galaxy array.

Can someone please be kind enough to tell me what I did wrong, or how do I fix it?
Thanks a lot and sorry for the trouble :P

here is my main.cpp
#include "Class&Functions.h"
#include <iostream>
#include <string>
using std:: cin;
using std:: cout;
using std:: endl;
using std:: string;
using namespace std;

void createGalaxy();
Star generateStar(int, int, string);

int main () {

	createGalaxy();

	return 0;
}

void createGalaxy () {

	int totalGalaxies;

	cout << "What is the total number of galaxies in "
			<< "the universe? ";
	cin >> totalGalaxies;

	while ((totalGalaxies < 0) || (totalGalaxies > 1000)) {
		cout << "Please try again [0-1000]";
		cin >> totalGalaxies;

	}

	Galaxy universe[totalGalaxies];

	string tempName;
	int tempStarCount;

	for (int i = 0; i < totalGalaxies; i++) {
		cout << "What is the name of galaxy " << i+1 << "? ";
		cin >> tempName;

		cout << "How many star(s) are in " << tempName << "? ";
		cin >> tempStarCount;

		cout << "Galaxy Created: " << tempName
		<< ", contain(s) " << tempStarCount
		<< " stars." << endl;

		for (int j = 0; j < tempStarCount; j++) {
			universe[i] = Galaxy (tempName, tempStarCount);
		}

	}

	cout << totalGalaxies << "galaxies Added to the universe:" << endl;

	for (int i = 0; i < totalGalaxies; i++)
		cout << universe[i].gettempName() << endl;

}

Star generateStar(int starID, int starCount, string starLocation) {

	return Star(0, 0, "0");
}




and here is my headers.h

#include <iostream>
#include <stdlib.h>
#include <string>
using std:: cin;
using std:: cout;
using std:: endl;
using std:: string;
using namespace std;

//Functions

class Star {
	int starID, starIlluminationDegree;
	string starLocation;

public:
	Star (int, int, string);

};

Star:: Star (int a, int b, string c) {
	this->starID = a;
	this->starIlluminationDegree = b;
	this->starLocation = c;

}

class Galaxy {
	string tempName;
	int size;
	Star *galaxy[500][500];

public:
	Galaxy();
	Galaxy(string, int);
	string gettempName();

};

Galaxy:: Galaxy (){


}

Galaxy:: Galaxy (string a, int B)/> {
	this->tempName = a;
	this->size = b;

}

string Galaxy:: gettempName() { return tempName;}




Is This A Good Question/Topic? 0
  • +

Replies To: Return Object in Function (C++) [syntax?]

#2 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 2039
  • View blog
  • Posts: 6,072
  • Joined: 05-May 12

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 11:43 AM

Describe the problem that you are running into.

In the meantime, you really should put the implementation of your Star and Galaxy methods into a .cpp file instead of leaving them in your header file.
Was This Post Helpful? 1
  • +
  • -

#3 lobsterEater  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 24
  • Joined: 15-July 12

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 11:51 AM

will i built the program fine in eclipse (MinGW). But when I try to run it, I get a prompt "Error exist in required project. Continue to Launch". My IDE haven't highlight out any line with invade code. So I am unsure what I did wrong. :S

UPDATE: Ok False Alarm XD Problem solved.
It was weird, I restarted my eclipse and now everything works. except my program crashes because the array is set to [500][500] in galaxy class. (its actually suppose to be at 1000x1000, and im only allowed to use array and pointers in this assignment) any idea on how to fix that?
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 2039
  • View blog
  • Posts: 6,072
  • Joined: 05-May 12

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 12:03 PM

Look at your line 34... Unless VLA's work differently, that line of code is going to use totalGalaxy * sizeof(Galaxy) of stack space. Now look at 31 of your header file. Each Galaxy uses at least sizeof(string) + sizeof(int) + (sizeof(Star *) * 500 * 500) bytes. 500 * 500 is already 250,000. Assuming 32 bit pointers, then you are up to at least 1MB just for a single Galaxy. I don't recall exactly now, but I think the default stack size for threads on Windows is 1MB.

The first step you can take is dynamically allocate your array of Galaxy in your function, and dynamically allocate your array of stars in your Galaxy class. The next step is instead of allocating huge arrays, allocate a small reasonably sized array and then grow the array as needed.

I have no idea, though, why you are allocating a 500x500 or 1000x1000 array of (Star *) in your Galaxy, and the in addition also have a location property on your Star class. Space is mostly empty space. Most of those entries in your Galaxy will remain unused. And besides... According to Carl Sagan, "There are billions upon billions of stars". :lol: Do you really want to allocate an array that large?

This post has been edited by Skydiver: 16 July 2012 - 12:08 PM

Was This Post Helpful? 1
  • +
  • -

#5 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 4951
  • View blog
  • Posts: 11,358
  • Joined: 16-October 07

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 12:10 PM

Perhaps:
Star generateStar(int starID, int starCount, string starLocation) {
	// why are returning this
	// and not using the parameters you passed?
	// return Star(0, 0, "0");
	// use the parameters?
	return Star(starID, starCount, starLocation);
}



However, you could just call your constructor. Why pointers in galaxy, btw? You might consider a sparse matrix if you're trying to save space. Hell, just use a vector and search if you need something. Wait, you're making it static size but then taking a size? Huh? If you want an x,y location, put it in the Star class.
Was This Post Helpful? 1
  • +
  • -

#6 lobsterEater  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 24
  • Joined: 15-July 12

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 12:16 PM

I'm kind of confused now. Attached is my assignment questions. Can you just quickly scan through it to make sure I'm on the right track?

From my understanding, I'm suppose to:
1. create a star class that contain info such as location, brightness and name of the galaxy its in.
2. add stars into a 1d array named galaxy (generate some info like brightness and x,y cord) unlimited size?
3. add galaxies to 2d array, also know as the universe. [1000][1000]

im only allowed to use array in this project. so... i'm not sure how else i can do that.

let me know if im understanding something wrong. english is not my first language. ^^

My prof specifically told me not to use containers so vector deque and linked list is all not in my option atm

thanks for the help guys :) i really appreciate it

Attached File(s)


Was This Post Helpful? 0
  • +
  • -

#7 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 4951
  • View blog
  • Posts: 11,358
  • Joined: 16-October 07

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 12:29 PM

So, galaxy has a 1d array?
struct Location { int x, y; };

struct Star { 
	// location, brightness and name of the galaxy its in
	Location loc;
	int brightness;
	// the star will belong to a galaxy, it needn't hold this information
};

struct Galaxy {
	std::string name;
	int count;
	Star *stars;
	Galaxy(); // if it's empty
	Galaxy(int count); // for when you put a star count
	~Galaxy(); // to free the memory in stars, if assigned
};

// this is sloppy, but per instructions
const int UNIV_WIDTH = 1000;
const int UNIV_HEIGHT = 1000;
typedef Galaxy Universe[UNIV_WIDTH][UNIV_HEIGHT];



Hope this helps.
Was This Post Helpful? 1
  • +
  • -

#8 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 4951
  • View blog
  • Posts: 11,358
  • Joined: 16-October 07

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 12:40 PM

Ok, just saw the PDF:
// For each galaxy, we store the list of its stars including their IDs, their locations, and the degree of their illuminations.
// 2. A list of stars for each galaxy including mentioned specifications for each star. This list is seen as a screen of stars.
struct Star { 
	int id, x, y, illumination;
};


// 1. A list of galaxies (seen only as a list) and their specifications
// We only need to store name and location(x,y) of galaxies in the universe and the list of their stars.

struct Galaxy { 
	std::string name;
	int x, y;
	Star *starList;
	int starListSize;
	Galaxy(); // if it's empty
	Galaxy(int); // for when you put a star count
	~Galaxy(); // to free the memory in stars, if assigned
};

struct Universe { 
	Galaxy *galaxies;
	int galaxiesSize;
	Universe(int);
	~Universe();
};



Note, this is partial. You'll probably want methods, etc, in those structures. But it's a start.
Was This Post Helpful? 1
  • +
  • -

#9 lobsterEater  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 24
  • Joined: 15-July 12

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 12:44 PM

Thanks Hagrid :D I'm going to try that out.
Was This Post Helpful? 0
  • +
  • -

#10 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 2039
  • View blog
  • Posts: 6,072
  • Joined: 05-May 12

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 01:51 PM

I guess I'm equally as confused as the OP.

There is this item under Programming Notes than suggests (requires?) using a 2D array to represent the screen of stars:

Quote

7. Implement the lists of galaxies and the screen of stars using two arrays, 1 dimensional and 2
dimensional, respectively.


Yet, the document starts out with:

Quote

Therefore, we have two data structures:
1. A list of galaxies (seen only as a list) and their specifications
2. A list of stars for each galaxy including mentioned specifications for each star. This list is seen as a screen of stars.

and continues on to say:

Quote

(Skipping the first paragraph on page 2)

We also have a list of stars for each galaxy and we need to keep track of all stars. The list of stars for each galaxy starts from the first star including its ID number, its location (x,y) in the universe, and its illumination degree(a random number between 1-100). The list continues with the second star and its information, and continues up to the last star in the galaxy. The following picture shows how you see the list of stars in a galaxy. [+20 marks]

As mentioned earlier, for each star in the list we need to store its ID number, its location, and its illumination degree. For each galaxy we store its name and information on where we can find its stars. (Think how to connect each galaxy in the first list with its stars in the screen, specially the first star.) [+20 marks]

All stars in each galaxy should be placed in random locations around the first star within 50 space units in X axis and 50 space units in Y axis. Bounds of our universe are 1,000 space units in each X and Y axes. [+5 marks]


What throws confusion is the the aforementioned Programming Notes #7, as well as the first paragraph on page 2 that I skipped:

Quote

Note that we need to have two structures for storing information: a list and a screen (Think what data structures in C++ are best suited.)


To me, I see no value to the 2D array screen other than to hog memory. The positions are already stored in the Star class, so the indices into the 2D array just duplicate data. If the OP has not yet learned about linked lists, (I have no idea what COMP 2401/COMP 1402 taught with regards to "structs"), then he ends up learn making an adhoc linked list by pointing from one screen element to the next.
Was This Post Helpful? 1
  • +
  • -

#11 lobsterEater  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 24
  • Joined: 15-July 12

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 02:34 PM

I'm trying to do everything in class style to get the "bonus marks".
As confused as I am atm, I've encountered another problem.

How do I add my galaxies into the universe?

Sorry if I'm asking stupid questions, I'm fairly new to C++ programing, and I literally cannot figure it out :S

main.cpp
#include "Class&Functions.h"
#include <iostream>
#include <string>
using std:: cin;
using std:: cout;
using std:: endl;
using std:: string;
using namespace std;

void createGalaxy();

int main () {

	createGalaxy();

	return 0;
}

void createGalaxy () {

	int totalGalaxies;

	cout << "What is the total number of galaxies in "
			<< "the universe? ";
	cin >> totalGalaxies;

	while ((totalGalaxies < 0) || (totalGalaxies > 1000)) {
		cout << "Please try again [0-1000]";
		cin >> totalGalaxies;

	}

	Universe universe(totalGalaxies);

	string tempName;
	int tempStarCount;

	for (int i = 0; i < totalGalaxies; i++) {
		cout << "What is the name of galaxy " << i+1 << "? ";
		cin >> tempName;

		cout << "How many star(s) are in " << tempName << "? ";
		cin >> tempStarCount;

		cout << "Galaxy Created: " << tempName
		<< ", contain(s) " << tempStarCount
		<< " stars." << endl;

		for (int j = 0; j < tempStarCount; j++) {
			//universe[i] = Galaxy (tempName, tempStarCount);
		}

	}

	cout << "===================================================" << endl
			<< totalGalaxies << " galaxies Added to the universe:" << endl
			<< "---------------------------------------------------" << endl;

	for (int i = 0; i < totalGalaxies; i++) {
		//cout << universe[i].gettempName() << ":" << endl;

	}

}




Class&Functions.h
#include <iostream>
#include <stdlib.h>
#include <string>
using std:: cin;
using std:: cout;
using std:: endl;
using std:: string;
using namespace std;

//Functions

//END of Functions

//Classes

class Star {
	int starID, starIlluminationDegree, x, y;
	string starLocation;

public:
	Star (int, int, int, int, string);

};

Star:: Star (int a, int b, int c, int d, string e) {
	this->starID = a;
	this->starIlluminationDegree = b;
	this->x = c;
	this->y = d;
	this->starLocation = e;

}

class Galaxy {
	string name;
	int size, x, y;
	Star *starList;

public:
	Galaxy();
	Galaxy(string, int, int, int, Star);
	string gettempName();

};


Galaxy:: Galaxy (string a, int b, int c, int d, Star e) {
	this->name = a;
	this->size = b;
	this->x = c;
	this->y = d;
	this->starList = &e;

}

string Galaxy:: gettempName() { return name;}

class Universe {
	Galaxy *galaxy;
	int galaxySize;

public:
	Universe(int);
};


Universe:: Universe (int a) {
	this->galaxySize = a;

}




Was This Post Helpful? 0
  • +
  • -

#12 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 2039
  • View blog
  • Posts: 6,072
  • Joined: 05-May 12

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 03:14 PM

I would have assumed that your teacher had covered lists stored in arrays before giving you this assignment that is due tomorrow. (Or is it today already in your timezone?)

Didn't you cover something like this?
class ListOfInts
{
public:
    ListOfInts(int maxSize)
        : _maxSize(maxSize)
        , _currentSize(0)
    {
        _values = new int[maxSize];
    }

    ~ListOfInts()
    {
        delete [] _values;
    }

    bool Add(int value)
    {
        if (_currentSize >= _maxSize)
            return false;    // actually we should throw an exception
        _values[_currentSize++] = value;
        return true;
    }

    int GetSize() const
    {
        return _currentSize;
    }

    int GetIthItem(int i)    // zero based
    {
        if (i >= _maxSize || i < 0)
            return -1; // actually we should throw an exception
        return _values[i]
    }

private:
    int * _values;
    int _maxSize;
    int _currentSize;
};


This post has been edited by Skydiver: 16 July 2012 - 03:43 PM

Was This Post Helpful? 1
  • +
  • -

#13 lobsterEater  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 24
  • Joined: 15-July 12

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 03:41 PM

nope, we haven't covered much. i had like 2 classes so far. and it is due tomorrow night 12 pm :)

still got more than a day. thanks for the code sample. it helps a lot ^^
Was This Post Helpful? 0
  • +
  • -

#14 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 4951
  • View blog
  • Posts: 11,358
  • Joined: 16-October 07

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 03:47 PM

Be nice to yourself. What does int, int, int, int, string tell you? Worse, what does int a, int b, int c, int d, string e mean?

This might be easier to follow
//objects.h

class Star {
	// don't you think "star" is silly for an object called star...
	int starID, starIlluminationDegree, x, y;
	string starLocation;

public:
	Star(int starID, int starIlluminationDegree, int x, int y, const std::string &starLocation);
};



Now, looking at the header, you know what you're looking for. Btw, how exactly do you know what the values stored in the class are if they're private?


Put the code here:
Star::Star(int id, int illum, int _x, int _y, const std::string &loc) :
	starID(id), starIlluminationDegree(illum), x(_x), y(_y), starLocation(loc)
{
}


Was This Post Helpful? 1
  • +
  • -

#15 lobsterEater  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 24
  • Joined: 15-July 12

Re: Return Object in Function (C++) [syntax?]

Posted 16 July 2012 - 04:03 PM

Sorry I didn't get it. Why would Star be a silly name for a class that represents stars? Isn't it logical?


Star::Star(int id, int illum, int _x, int _y, const std::string &loc) :
	starID(id), starIlluminationDegree(illum), x(_x), y(_y), starLocation(loc)
{
}



This is something in the coding style I don't quit understand.
Star:: star means it sets sort of a function within the Star class known as Star...
Than it defines the attributes (int id, int illum, int _x, int _y, const std::string &loc)
but what does this mean? starID(id), starIlluminationDegree(illum), x(_x), y(_y), starLocation(loc)
what does the : do? in java its like if or else for comparing (if i remember correctly) eg. x < y ? return 0 : return 1

how does it work in c++?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2