CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13
  1. #1
    Join Date
    May 2004
    Posts
    28

    Lots of small [interesting] questions or "odds of C++ ?"

    Greetings all,

    Just a few intro words. I'm not new to programming, but I am sort of to C++. It's just that I didn't learn it as things are usually learnt (I read a little of this, a little of that, etc..), so I got tired of this and decided to learn it well once and for all. Now, I love C++ (who doesn't eh? ), but coming from Java and Delphi/Object Pascal some things just freaking me out about C++. With C++ being the most flexible language of all times, why in the world there's so much troubles with the arrays!? I mean, what gives, there isn't even a specific function defined which returns the size of the array! Thank God there's sizeof But wait, even that is screwed up! Read on

    Anyway, I'm sure something of what I'm going to ask has already been asked and most likely replied, but I have quite a few small questions so I thought I'd create a new thread, and will later on add my "small" questions here as they appear.

    Also, please notice my questions are of the "why" nature, in most of the cases I know the solutions, I just want to know WHY it is like this in C++, indepth explanations are more than welcome too

    Ok, in no specific order:

    // Problem #1 ----------------------------------------------------------
    // {

    This code works:

    Code:
    #include <iostream>
    
    using namespace std;
    
    const int ARR_SIZE = 9;
    
    int main()
    {
    	long arr[ARR_SIZE];
    	int arr_length;
    
    	for (int i=0; i<ARR_SIZE; i++)
    	{
    		arr[i] = i;
    	}
    
    	arr_length = sizeof(arr)/sizeof(arr[0]);
    	cout << arr_length << endl;
    
    	return 0;
    }
    Output:
    Code:
    9
    Press any key to continue


    Why doesn't the following code work? :

    Code:
    #include <iostream>
    
    using namespace std;
    
    const int ARR_SIZE = 9;
    
    template <class T>
    int arr_len(T* arr)
    {
    	return sizeof(arr)/sizeof(arr[0]);
    }
    
    int main()
    {
    	long arr[ARR_SIZE];
    	int arr_length;
    
    	for (int i=0; i<ARR_SIZE; i++)
    	{
    		arr[i] = i;
    	}
    
    	arr_length = arr_len(arr);
    	cout << arr_length << endl;
    
    	return 0;
    }
    Output:
    Code:
    1
    Press any key to continue
    I mean it compiles just fine, but the result is always "1". Which btw would be logical since the NAME of the array is the POINTER to its first element, so:
    sizeof(arr)/sizeof(arr[0]);
    in the case of the arr_len function sizeof(arr) and sizeof(arr[0]) is one and the same thing, and the result of course is *one* (1), but why then does the compiler treat the name of the array in main() function as sizeof(arr[X])*ARR_SIZE, where X = number of any element in the "arr" array ?
    Amazing

    // } // end of problem #1


    // Problem #2 ----------------------------------------------------------
    // {

    We all know that there are dynamic arrays and static arrays. In Delphi I have absolutely NO problems with arrays as they're super flexible. Delphi supports both 1) dynamic arrays, 2) static arrays and 3) static arrays which can be allocated during run-time. Dynamic arrays are not supported by Java, by I can bypass this problem by creating a new array and copy data from one array to the other, approximately like this (Java pseudocode):

    Code:
    int arr1[];
    int user_value;
    user_value = get_int_from_user();
    arr1 = new int[user_value];
    
    int arr_size = length(arr1);
    int arr2[];
    arr2 = new int[arr_size*2];
    
    for (int i=0; i<arr_size; i++)
    {
        arr2[i] = arr1[i];
    }
    Both arr1 and arr2 are static arrays, but their size is UNKNOWN until *run-time*, so you can guess that using the above technique I can code a function which will change the size of the array, which will make an illusion of a dynamic array.
    Now in C++ I can't even do that ! Please don't go telling me about STL's vector class (I know it's "dynamic"), I'm concerned about usual arrays. Why can't this bit of code just work?

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int size;
    	cout << "Please input an integer: ";
    	cin >> size;
    	int arr[size];
    
    	return 0;
    }
    YES, I can do it this way:

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int size;
    	cout << "Please input an integer: ";
    	cin >> size;
    	int* arr;
    	arr = new int[size];
    
    	return 0;
    }
    and that's cool, BUT take a look at problem #3 then

    // } // end of problem #2

    // Problem #3 ----------------------------------------------------------
    // {
    Assume we have the following code, which works just fine:

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int test;
    	test = 7;
    	int* ptrInt= &test;
    
    	cout << "The address of \'test\' value = " << ptrInt;
    	cout << "\nThe value of \'ptrInt\' pointer = " << *ptrInt << endl;
    
    	return 0;
    }
    Now I want to create an ARRAY OF POINTERS to int type. Okay, this works:

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int* arr[3];
    	int var1 = 1;
    	int var2 = 2;
    	int var3 = 3;
    	arr[0] = &var1;
    	arr[1] = &var2;
    	arr[2] = &var3;
    
    	cout << "Contents of the array:\n";
    	cout << arr[0] << endl;
    	cout << arr[1] << endl;
    	cout << arr[2] << endl;
    
    	return 0;
    }
    But now I have that situation when size of the array is not known until run-time, so I do the following (this code DOES NOT WORK):

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int size;
    	cout << "Please input an integer: ";
    	cin >> size;
    	int* arr;
    	arr = new int[size];
    	int var1 = 1;
    	int var2 = 2;
    	int var3 = 3;
    	arr[0] = &var1; // ERROR: CANNOT CONVERT FROM int* to int
    	arr[1] = &var2;// ERROR: CANNOT CONVERT FROM int* to int
    	arr[2] = &var3;// ERROR: CANNOT CONVERT FROM int* to int
    
    	cout << "Contents of the array:\n";
    	cout << arr[0] << endl;
    	cout << arr[1] << endl;
    	cout << arr[2] << endl;
    
    	return 0;
    }
    Why has the array become a usual INT type array? How do I create an array of pointers to say INT type using the new operation which lets me allocate array's size during run-time?

    } // end of problem #3


    // Problem #4 ----------------------------------------------------------

    This code works just fine and destructor is called:

    Code:
    #include <iostream>
    
    using namespace std;
    
    class foo
    {
      private:
        int data;
      public:
        foo(int);
        ~foo();
    };
    
    foo::foo(int value) : data(value) {}
    
    foo::~foo()
    {
    	cout << "Message from destructor.\n";
    }
    
    int main()
    {
    	foo dummy(3);
    
    	return 0;
    }

    Output:
    Code:
    Message from destructor.
    Press any key to continue
    This code works just fine too and destructor is called as well:

    Code:
    #include <iostream>
    
    using namespace std;
    
    class foo
    {
      private:
        int data;
      public:
        foo(int);
        ~foo();
    };
    
    foo::foo(int value) : data(value) {}
    
    foo::~foo()
    {
    	cout << "Message from destructor.\n";
    }
    
    int main()
    {
    	foo* dummy = new foo(3);
    	delete dummy;
    
    	return 0;
    }
    Output:
    Code:
    Message from destructor.
    Press any key to continue
    And here's what I'm concerned about. For example I allocate memory using operator "new" the following way:

    Code:
    #include <iostream>
    
    using namespace std;
    
    class foo
    {
      private:
        int data;
      public:
        foo(int);
        ~foo();
    };
    
    foo::foo(int value) : data(value) {}
    
    foo::~foo()
    {
    	cout << "Message from destructor.\n";
    }
    
    int main()
    {
    	foo& ref = *(new foo(3));
    
    	return 0;
    }
    Output:
    Code:
    Press any key to continue
    As you can see no destructor is called automatically. And I can't use delete operation to a reference variable. Problem - how do I free memory after allocating it this way?

    } // end of problem #4

    Okay, I have a lot more questions, but I'm already tired of typing I'll post more sometime later, and meanwhile, any help would be greatly appreciated

    Oleg
    Last edited by Xatrix; October 18th, 2005 at 08:28 AM.

  2. #2
    Join Date
    Sep 2005
    Location
    New Delhi, India
    Posts
    332

    Re: Lots of small [interesting] questions or "odds of C++ ?"

    Quote Originally Posted by Xatrix
    but why then does the compiler treat the name of the array in main() function as arr[X]*ARR_SIZE, where X = number of any element in the "arr" array ?
    You are basically passing address of array to function....and there when you write sizeof(arr) it gives you 1...as you also said......but in main when you do sizeof(arr)....here arr is not just a simple pointer...its a constant pointer which has a special meaning to compiler...compiler automatically interprets that
    Appreciate others by rating good posts

    "Only buy something that you'd be perfectly happy to hold if the market shut down for 10 years." - Warren Buffett

  3. #3
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725

    Re: Lots of small [interesting] questions or "odds of C++ ?"

    I didn't read everything, but the main problem is you are using C-style
    arrays. You should start by using C++ constructs, and go back to
    low-level C coding only when necessary.

    Take a look at the vector class. It is a dynamic array class.

    See the CodeGuru article:

    http://www.codeguru.com/Cpp/Cpp/cpp_...cle.php/c4027/

  4. #4
    Join Date
    Apr 2005
    Location
    Norway
    Posts
    3,934

    Re: Lots of small [interesting] questions or "odds of C++ ?"

    1.
    in the case of the arr_len function sizeof(arr) and sizeof(arr[0]) is one and the same thing, and the result of course is *one* (1), but why then does the compiler treat the name of the array in main() function as sizeof(arr[X])*ARR_SIZE, where X = number of any element in the "arr" array ?
    It is not 1/1, it is the size of the pointer (4 bytes) divided by the length of the frist element which is a long (4 bytes).

    In the main funtion 'name' reprepresent a static array, and in that case the sizeof-operator return the "satically allocated length".

    3.
    To create an array of ptr-to-ints you can do this:
    Code:
    int** ppInt = new int*[size];
    4.
    Here you're just trying to make problems... anyway... why not just cast the reference back to a pointer, then delete the pointer.

    - petter

  5. #5
    Join Date
    Sep 2005
    Location
    New Delhi, India
    Posts
    332

    Re: Lots of small [interesting] questions or "odds of C++ ?"

    Quote Originally Posted by Xatrix
    #include <iostream>

    using namespace std;

    int main()
    {
    int size;
    cout << "Please input an integer: ";
    cin >> size;
    int arr[size];

    return 0;
    }
    Who says this won't work...works perfectly fine
    Appreciate others by rating good posts

    "Only buy something that you'd be perfectly happy to hold if the market shut down for 10 years." - Warren Buffett

  6. #6
    Join Date
    Jan 2001
    Posts
    588

    Re: Lots of small [interesting] questions or "odds of C++ ?"

    First of all, you need to get a C++ book if you're serious about learning the language. For people who have a Java background, many things may seem strange, but there is reasoning behind them. I would recommend "Accelerated C++" as a good text.

    Anyway, onto your questions:

    Problem 1: The arr_len() function in your example receives just a pointer. A pointer is nothing but a memory address; since the function just receives the pointer as a paramter, it has no idea where the pointer came from or what it points to. Therefore, sizeof() in this case will return the number of bytes occupied by the pointer itself. Since your array contains longs, and it seems on your platform a long is the same size as a pointer, sizeof(arr) == sizeof(arr[0]), and 1 is returned.

    In the first example, the array was statically allocated on the stack within the same scope as the call to sizeof(). In this case, the compiler is able to determine how large the array is, because it knows exactly where it came from (the declaration of the array is within the same block as the call to sizeof()). Because of this, it returns what you would expect, which is the number of bytes occupied by the entire array.

    Problem 2: Don't get caught up in terminology; arrays are arrays. You can declare arrays in different ways, but once you do, arrays behave the same way (except for some caveats with respect to destruction which I'll get to). Incidentally, your second-to-last example in Problem 2 would compile on a C99-compliant compiler. If you want to allocate an array whose size is not known until runtime, then you need to use the syntax that you gave in your last example in this section.

    And, don't dismiss std::vector; it is the preferred way of working with dynamically-sized arrays. It takes care of all this business for you so you can spend more time worrying about the rest of your code. If you looked at the source code for a vector implementation, you would find that it uses the new-operator syntax to allocate memory at runtime.

    Problem 3: If you want an array of pointers, then you need to allocate an array of pointers. In your last code example, you allocated an array of ints, not int *'s. However, are you sure you really want an array of pointers? I realize that your examples are just for illustration, but an array of plain old ints would do the same job and would be less confusing for you.

    Code:
    int size;
    cin >> size;
    int **arr; // note that this is a pointer-to-pointer, because it will point at an array of pointers
    arr = new int*[size];
    int var1 = 1, var2 = 2, var3 = 3;
    arr[0] = &var1;
    arr[1] = &var2;
    arr[2] = &var3;
    You have to be careful in cases such as these because once the execution of the program leaves the scope where var1, var2, and var3 are declared, the pointer values stored in the arr array are no longer valid.

    Problem 4: If you allocate memory using new, you need to delete it, period. In your case, you could do this:

    Code:
    foo &ref = *(new foo(3));
    delete &ref;
    References have the same semantics as actual objects, so you can use the address-of operator to get the address of the pointer you allocated.


    As I said, I suggest that you read a good C++ book. People who have experience in other languages (especially Java) tend to want to apply these other languages' concepts in their C++ code. This can manifest itself, for instance, in overusing the new operator, allocating everything from the free store, much like Java does. This is not the best way to write a C++ program. A good C++ programmer only uses new/delete when necessary and uses container classes (like std::vector) to eliminate the hassle of maintaining dynamic memory whenever possible. Different languages have different paradigms for getting things done; you just need to be introduced to the "C++ way."

  7. #7
    Join Date
    Dec 2004
    Location
    Poland
    Posts
    1,165

    Re: Lots of small [interesting] questions or "odds of C++ ?"

    about 3:
    Code:
    int* arr;
    arr = new int[size];
    int var1 = 1;
    int var2 = 2;
    int var3 = 3;
    arr[0] = &var1; // ERROR: CANNOT CONVERT FROM int* to int
    This happens because you are trying to insert an int* to array containing int. To do what you needd you should use
    Code:
    std::vector<int*> arr; //vector of pointers
    int var1 = 1;
    int var2 = 2;
    int var3 = 3;
    arr.push_back(&var1);
    About 4:
    Code:
    foo& ref = *(new foo(3));
    You create object which is never destroyed. Reference itself dies when program ends, but object still persosts, becqause it is not deleted. No destructor called.

    Let me take a closer look at the rest of questions, and I will try to explain them.
    Hob
    Last edited by Hobson; October 18th, 2005 at 09:08 AM.
    B+!
    'There is no cat' - A. Einstein

    Use &#91;code] [/code] tags!

    Did YOU share your photo with us at CG Members photo gallery ?

  8. #8
    Join Date
    Jan 2001
    Posts
    588

    Re: Lots of small [interesting] questions or "odds of C++ ?"

    Quote Originally Posted by sunnypalsingh
    Who says this won't work...works perfectly fine
    This will only work on either a C99-compliant compiler or a compiler with proprietary extensions to support this (I seem to remember that GCC has the ability to do this if you want). It is not part of the C++98 standard.

  9. #9
    Join Date
    Sep 2005
    Location
    New Delhi, India
    Posts
    332

    Re: Lots of small [interesting] questions or "odds of C++ ?"

    Quote Originally Posted by Bob Davis
    This will only work on either a C99-compliant compiler or a compiler with proprietary extensions to support this (I seem to remember that GCC has the ability to do this if you want). It is not part of the C++98 standard.
    yes you are right...i tried to run it on DEV C++ it worked fine as it is C99 compliant....but didn't worked on VC 6.0...i guess it's not C99 compliant
    Appreciate others by rating good posts

    "Only buy something that you'd be perfectly happy to hold if the market shut down for 10 years." - Warren Buffett

  10. #10
    Join Date
    Feb 2005
    Location
    "The Capital"
    Posts
    5,306

    Thumbs up Re: Lots of small [interesting] questions or "odds of C++ ?"

    This is going to a very cumbersome thread with so many questions quoted in one. You should have had taken each at a time as well as searched for answers to questions that have been already answered in this forum a zillion number of times like the Problem#1.

    Solution to Problem#1:

    When you use sizeof it depends on the parameter on which this operator works. In this first case it works with an actual array - "arr" but in the second case it is associated with an pointer of type T. There is a lot of responsibility on the sizeof operator in that it has to give the size of the array's as well as pointers. And hence this dissimilarity in your observations. Also, this is one of the many reasons why std::vector is suggested as the superior and more elegant solution as compared to arrays.

    Solution to Problem#2:

    I dont know how Java or Delphi arrays work but the thing is pretty simple. If you dont know if an array is some particular size at compile time then you cannot make a static array i.e. something stored on the stack. For that you need to have a dynamic array. And in other languages may be that is the way they implemented except for the fact that these implementations are hidden from you. You could also do something like that by using encapsulation and a little bit of dynamic memory allocations using new operator and a little tinch of auto_ptrs or other smart pointers as appropriate.

    Solution to Problem#3

    The code that you have supplied is incorrect in many ways but I won't wonder about them and comment directly on your issue. The thing is it does not becomes the usual int type array by itself. It has become so because you have asked it to behave as that. To have a dynamically allocated array to store pointers to int you will have to do something like:
    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
    	int size;
    	cout << "Please input an integer: ";
    	cin >> size;
    	int** arr;
    	arr = new int*[size];
    	int var1 = 1;
    	int var2 = 2;
    	int var3 = 3;
    	arr[0] = &var1; // ERROR: CANNOT CONVERT FROM int* to int - Now you can
    	arr[1] = &var2;// ERROR: CANNOT CONVERT FROM int* to int - Now you can
    	arr[2] = &var3;// ERROR: CANNOT CONVERT FROM int* to int - Now you can
    
    	cout << "Contents of the array:\n";
    	cout << arr[0] << endl;
    	cout << arr[1] << endl;
    	cout << arr[2] << endl;
    
    	return 0;
    }
    The code here and the one you showed is missing a delete on the dynamic allocation which suffices the fact that you have a Java background. Also there is no bound checking before the printing of the array elements. Beware of those issues. (I couldnt stop myself).

    Solution to Problem#4

    You could simply call a delete as :
    Code:
    	delete (&ref);
    Hope this helps. Regards.

    //EDIT : Seems like many people beat me to it while I was composing the post.
    Last edited by exterminator; October 18th, 2005 at 09:44 AM. Reason: typo!

  11. #11
    Join Date
    Feb 2005
    Location
    Normandy in France
    Posts
    4,590

    Re: Lots of small [interesting] questions or "odds of C++ ?"

    Quote Originally Posted by sunnypalsingh
    yes you are right...i tried to run it on DEV C++ it worked fine as it is C99 compliant....but didn't worked on VC 6.0...i guess it's not C99 compliant
    Variable size arrays are a C99 feature, but not a C++ feature.
    So, a strict ISO C++ compiler does not support variable size arrays.
    However, a C99-compliant C/C++ compiler will probably support variable-size arrays in a C++ program, when compiling in non-strict mode.
    GCC, for example, support variable size arrays in C++ programs, and emit a warning if the "-pedantic" option is set.

    But, Comeau (i tried with the online version), even in relaxed mode, does not accept variable-size arrays in a C++ program, but accepts them in a C program.

    So, it is preferable to never use variable size array in a C++ module; instead, you should use std::vector.

    For a C module, that is different, and variable size arrays may help the programmer's task.
    "inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
    Club of lovers of the C++ typecasts cute syntax: Only recorded member.

    Out of memory happens! Handle it properly!
    Say no to g_new()!

  12. #12
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Lots of small [interesting] questions or "odds of C++ ?"

    Quote Originally Posted by Bob Davis
    First of all, you need to get a C++ book if you're serious about learning the language. For people who have a Java background, many things may seem strange, but there is reasoning behind them. I would recommend "Accelerated C++" as a good text.
    Also, if they are really interested on why C++ is the way it is, they should read "Design and Evolution of C++" by Bjarne Stroustrup.
    People who have experience in other languages (especially Java) tend to want to apply these other languages' concepts in their C++ code. This can manifest itself, for instance, in overusing the new operator, allocating everything from the free store, much like Java does. This is not the best way to write a C++ program.
    I would say it is one of the worst ways to create a C++ program. You can also bet that the C++ program is full of memory leaks also (as one of the examples by Xatrix demonstrates -- no call to "delete[]").

    Just to add my two cents:

    The major mistakes I have seen by Java programmers attempting to use C++ is

    1) Using the lowest level of C programming when not necessary.

    2) Attempting to write C++ classes that mimic what Java does (for example, "Object" classes or writing their own "vector" class).

    3) Using "new" an excessive number of times, where it is not necessary and invariably causes memory leaks (because of the lack of the call to "delete")

    4) Overusage of exceptions. In Java, programmers throw exceptions for seemingly anything that can go wrong, even in cases where it isn't really an "exceptional" condition. In C++, you should only throw exceptions for exceptional errors, i.e. errors that under normal conditions should never occur, but occur anyway.

    The Java-to-C++ programmer makes these mistakes because they are not aware C++ uses a different paradigm and in some cases, not knowing that C++ has the facilities they are looking for, and all they need to do is use standard library.

    Bottom line is that the Java programmer learning C++ should resist the attempt of using Java techniques in a C++ program. Maybe not techniques in terms of general programming (i.e. breaking up a large function into smaller functions, code refactoring, etc.) but in specific Java techniques such as I outlined above.

    Another minor error that I see Java programmers make:
    Code:
    //Calling the constructor of the base object, thinking that they are 
    //constructing the same object:
    class Base
    {
       public:
           Base(int x) { }
           Base() { }
    };
    
    class Derived : public Base
    {
        public:
            Derived() 
            {
                  Base(x);  // this does not call the parent Base constructor
            }
    };
    If I had a dollar for every every time a Java programmer makes this mistake, I would be rich.

    Regards,

    Paul McKenzie

  13. #13
    Join Date
    May 2004
    Posts
    28

    Re: Lots of small [interesting] questions or "odds of C++ ?"

    Thanks a lot everyone for all the replies! I very much appreciate the time you're taking to write all this!

    Ok, first off I'm using Microsoft's compiler and Visual Studio 6.0 with Service Pack 6 (installed it after I found out the problem with friend functions being an issue in the initial release).

    Secondly, I *have* just read (from A to Z) a wonderful C++ book written by Robert Lafore which is called "Object-Orientated Programming in C++", the best book about programming language I've ever read this far, I do recommend it to all new C++ programmers, but nonetheless, thanks for the tips about other books, I will look into some.

    As for Java style or C style programming. I haven't actually programmed in plain C, so I don't tend to write the C-style, quite the opposite, the things which I *know* are now depricated in C++, I try not to use them, e.g. #define, printf and other things like that (sorry to C fans). And I'm not trying to program in C++ the Java-style, it's just that I want to find out how to do *usual and simple* things in C++ which I did in those languages.

    Sorry about the forgotton delete[] operation

    Thanks about:
    foo& ref = *(new foo(3));
    delete &ref;

    Now how didn't I think of that? I just tried delete ref without thinking what delete needs as a parameter.


    Also thanks for this tip:
    int** arr = new int*[size];

    Although I read about pointers to pointers, but lack of use of them made me forgot about this, but it's starting to make sense now, especially when taking a closer look at the above line of code

    As for using the new operation excessive number of times, that might happen with Java programmers coming to C++, yes, but that's because any object in Java is created using new operation, and it seems very odd for us that in C++ you can simply write:
    MyClass obj;
    and that will CREATE an object, and I admit that as a Java programmer it's hard to accept that. I stand Java's syntax on this issue. Maybe that's why I "like" to use new directive. And what I've described in problem #4 is to eliminate the need to access class functions and class fields using the -> operation. To sum it all up, the following code is what does not hurt my eye:

    MyClass& ref = *(new MyClass);
    ref.some_method();
    delete &ref;


    So I prefer the above to:

    MyClass obj;
    obj.some_method();


    Although it's obvious C++'s "new" and Java's "new" operation is not one and the same thing. But I want to program C++ the right way, so most likely I'll get used to the method without using new where not necessary.

    wildfrog, Bob Davis and others, thanks about explaining about #1, got it now And yes Bob, those are just illustrations, of course an array of pointers to int does little sense if any.



    Oh and Paul M., I indeed often call Base class constructor in Java that way, but yes, what you've written doesn't work, but with a little modification it does:


    Code:
    #include <iostream>
    
    using namespace std;
    
    class Base
    {
       public:
           Base(int val) 
    	   {
    			cout << "Base constructor. Passed value = " << val << endl;
    	   }
    };
    
    class Derived : public Base
    {
    	public:
            Derived(int xval) : Base(xval) {}
    };
    
    
    int main()
    {
    	int x = 7;
    	Derived d(x);
    
    	return 0;
    }
    Also, I must admit it's new syntax to me, I have no idea why this:

    Derived(int xval) : Base(xval) {}

    is not the same as this

    Derived(int xval)
    {
    Base(xval)
    }



    Thanks again everyone, I will return with new questions
    Oleg
    Last edited by Xatrix; October 18th, 2005 at 01:25 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured