Thread: Class Use

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #7
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Here is an example of using an array to store some data:
    Code:
    #include <iostream>
    using namespace std;
    
    void show(int num[], int size)
    {
    	for(int i = 0; i<size; i++)
    	{
    		cout<<num[i]<<" ";
    	}
    	cout<<endl;
    }
    
    int main()
    {
    	const int size = 3;
    	int numbers[size] = {10, 20, 30};
    	show(numbers, size);
    
    	return 0;
    }
    However, with an array all the data must be of the same type, in this case int's. With a class, you can store different types of data in it:
    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    
    class Data
    {
    public:
    	int num1;
    	double num2;
    	string str;
    };
    
    
    void show(Data aDataObj)
    {
    	cout<<aDataObj.num1<<" "<<aDataObj.num2<<" "<<aDataObj.str<<endl;
    }
    
    
    int main()
    {
    	Data myData;
    
    	myData.num1 = 10;
    	myData.num2 = 3.5;
    	myData.str = "hello";
    
    	show(myData);
    
    	return 0;
    }
    So, to start, you can think of a class as an array that can store different types of values.
    Last edited by 7stud; 04-06-2006 at 01:18 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Class design problem
    By h3ro in forum C++ Programming
    Replies: 10
    Last Post: 12-19-2008, 09:10 AM
  2. Two conceptual questions
    By AntiScience in forum C++ Programming
    Replies: 3
    Last Post: 11-01-2007, 11:36 AM
  3. Defining derivated class problem
    By mikahell in forum C++ Programming
    Replies: 9
    Last Post: 08-22-2007, 02:46 PM
  4. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 AM