vijayan121 1,152 Posting Virtuoso

> But how do I go thru A folder and get all the files size's that are inside?

See: http://www.daniweb.com/forums/post342872.html#post342872

That just prints the native_file_string. To get the file size, construct a boost::filesystem::path from iter->native_file_string() and then use boost::filesystem::file_size on it, as in your current code.

vijayan121 1,152 Posting Virtuoso
void Example::function1( const Example& ex )
{
    // copy of the object on which function1 is called
    Example copy_of_this( *this ) ;

    /* whatever */

}
vijayan121 1,152 Posting Virtuoso

simply

int main()
{
    Example doe;
    
    doe.function1(doe);
}

or

int main()
{
    Example doe;
    Example water(doe);
    
    doe.function1(water);
}
vijayan121 1,152 Posting Virtuoso
void Example::function1( const Example& ex )
{
    Example copy_of_ex( ex ) ;

    /* whatever */

}
vijayan121 1,152 Posting Virtuoso
class cIsBad : public [b]std::[/b]unary_function <T, bool> {
vijayan121 1,152 Posting Virtuoso

> After spending more than a year learning C++ , I now realise that
> I still don't know it enough to program safely with that language.

That is almost certainly incorrect. To be able to program well (safely, elegantly, efficiently) in a language does not imply that you have to know 'everything' about the language.

To quote Stroustrup:

What design and programming techniques do we want to emphasize? What subsets of the language do we want to learn first? What subsets of the language do we want to emphasize in real code?

...

Even for the professional programmer, it is impossible to first learn a whole programming language and then try to use it. A programming language is learned in part by trying out its facilities for small examples. Consequently, we always learn a language by mastering a series of subsets. The real question is not ‘‘Should I learn a subset first?’’ but ‘‘Which subset should I learn first?’’

...

The emphasis for both novices and experienced programmers should be concepts and techniques. The syntactic and semantic details of C++ are secondary to an understanding of design and programming techniques that C++ supports.

- from http://www.research.att.com/~bs/new_learning.pdf

> Even more depressing is that EVEN a company like Microsoft with
> billions of dollars of spending in research, easy access to any
> computer scientist in the world, can't figure correctly how C++ works.

Not really. The Microsoft C++ team has known …

vijayan121 1,152 Posting Virtuoso

> the problem lies with the implicit assignment int T::*PM to &B::i
> when the template is instantiated at compile-time.

Well, no assignment to an l-value is possible at compile time. At compile time, the constant expression &B::i is specified as the second template parameter.

A pointer to member constant expression shall be created using the unary & operator applied to a qualified-id operand, optionally preceded by a pointer to member cast

> At that point B is not well formed
B is just an incomplete type at that point. There is nothing in B so far to make it ill-formed.

> therefore the compiler don't know what B::i is and therefore complains:
The compiler knows (or ought to know) at that point that B::i is a non-static public member of B of type int.

The potential scope of a name declared in a class consists not only of the declarative region following the name's declarator, but also ...{elided}.

A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S.

> The nested class is: A< B, &B::i > which is being instantiated INSIDE B.
> The enclosing class here is B.

No.

A class defined within another is called a nested class. The name of a nested class is local to its enclosing class. The nested class is in the scope of its enclosing class. Except …

vijayan121 1,152 Posting Virtuoso

> Problem! That code WON'T compile in microsoft visual C++ 2008
> issuing specifically the C2327 compiler error:
> "'symbol' : is not a type name, static, or enumerator
> Code within a nested class attempts to access a member of the
> enclosing class that is not a type name, a static member, or an enumerator

Clearly, that is a spurious error message. In that code, there is no nested class is at all, and therefore there is no enclosing class either.

The IS clearly states that:

After the point of declaration of a class member, the member name can be looked up in the scope of its class. [Note: this is true even if the class is an incomplete class.]

It also gives an example (elided for clarity):

class Y;
char Y::* pmc;

declares pmc to be a pointer to a member of Y of type char. The declaration of pmc is well-formed even though Y is an incomplete type.

The code compiles cleanly under various versions of the GNU compiler, the Comeau compiler and other compilers with an EDG front end. AFAIK, the Microsoft C++ compiler which does not compile it is non-conforming for this case.

vijayan121 1,152 Posting Virtuoso

1) The iterator
a) why do you have a last_element member? Why don't you just return NULL for the before first element or after last element? I suspect you might have done that because of reverse iterations but even then I don't see why the much simpler NULL wouldn't work just as well.

The iterator corresponding to end is one which 'point to' a fictitious one past the last element of the sequence. This iterator must be well defined; --end should move the iterator to the last element of the sequence

b) why didn't you just put the insert_into_list and remove_into_list function INSIDE the iterator?

Insert and erase are logically operations on sequences; not operations on an iterator which just identifies one element of a sequence. Of course it is possible to create a pseudo sequence container and put insert and erase and other container operations into it.

2) I would have like you to have your opinion on a possible future revision of C++ to permit the pointer_to_member inside its own class

A pointer to member inside its own class is already allowed. eg.

template< typename T, int T::*PM > struct A {} ;
struct B
{
    int i ;
    A< B, &B::i > a ;
};

3) You seem to confirm that the last suggestion I proposed is the best approach, and you also mentionned "polymorphic call wrappers": I would be delighted to hear more about what that is! Do you mean to replace …

vijayan121 1,152 Posting Virtuoso

> wish list:
> -no additional memory cost for each item
> -keeps double-link list structures (no vectors, etc...)
> -no supplementary indirection cost allowed
> -no more "typing" when using it
> -a solution that is simple, logical and semantically elegant

I have a very large group of items which are linked to each other by different double link lists and trees using members inside each item.

what we really want to have is a sort of "super-iterator" to iterate through the items in different ways

Yes, what we want are ways to access these items as different sequences. A set of polymorphic iterators which can iterate through the same items as different sequences.

there is an additional (invisible) indirection created by the virtual dispatch when you move using the super_iterator.

So we will make them polymorphic at compile-time using the earlier pointer to member idea. The example below is just for the doubly linked list like sequences.

#include <iostream>
#include <iterator>
#include <algorithm>

// iterator over a sequence using pointers to members 
// for next element and prev element
template< typename T, T* T::*NEXT, T* T::*PREV >
struct list_iterator : std::iterator<std::bidirectional_iterator_tag,T*>
{

    list_iterator( T* curr, T* last ) : current(curr), last_element(last) {}

    T*& operator* () { return current ; }

    list_iterator& operator++ ()
    { current = current->*NEXT ; return *this ; }

    list_iterator& operator-- ()
    { current = current ? current->*PREV : last_element ;  return *this ; }

    list_iterator operator++ …
vijayan121 1,152 Posting Virtuoso

> But, what do you do when T is "list"
> For example: list_base<list>

> You get the annoying recursion problem again!
> Anyother great idea on this?

Perhaps you should first describe the real problem that you are trying to solve. It might, just might, have a much easier solution.

vijayan121 1,152 Posting Virtuoso

> Is it just a syntax problem to be amended in a future revision of C++
> or is there some underlying theoretically reason that I haven't think about?

There is an underlying theoretical reason, and you have already thought about it.

A pointer to member of a class cannot be introduced before the class is at least declared.

// error: `undeclared_class' has not been declared
int undeclared_class::*pointer_to_member ; 

struct declared_class ;
// fine: `declared_class' has been declared
int declared_class::*pointer_to_member ;

In this case, just to declare the class we need a pointer to member of that class which is not yet declared (which we are trying to declare).

You also have a discovered the solution; split this into two classes.

#include <iostream>

template < typename T > struct list_base
{
    explicit inline list_base( T* a = 0, T* b = 0 ) 
        : member_a(a), member_b(b) {}

    T* member_a ;
    T* member_b ;
    // ...
};

template < typename T, T* list_base<T>::*PTR_MEMBER > 
struct list : list_base<T>
{
    explicit inline list( T* a = 0, T* b = 0 ) 
       : list_base<T>(a,b) {}

    inline T* get() { return this->*PTR_MEMBER ; }

    // ...
};

template < typename T, T* list_base<T>::*PTR_MEMBER >
inline T* get_it( list<T,PTR_MEMBER>& lst ) 
{ return lst.*PTR_MEMBER ; }

int main()
{
    int a = 11111, b = 22222 ;

    list<int,&list_base<int>::member_a> lst1( &a, &b ) ;
    list<int,&list_base<int>::member_b> lst2( &a, &b ) ;

    std::cout << *lst1.get() << '\t' << *get_it(lst1) << '\n' …
vijayan121 1,152 Posting Virtuoso

[I want two different instances of the list (one with member_one and the other with member_two) and a single instance of the function. I want it done inside the list class itself (using nested class if necessary) and I want the pointer_to_member to be used as the template argument to create the two different template instances of the class) so that you could instantiate the list class twice like this:

If that is all you want, you do not need the pointer_to_member as a template parameter at all - just pass it to the constructor of the list. Then you could have either a member function or a free function do what you want.

#include <iostream>

template < typename T > struct list
{
    explicit list( T* list::*pm, T* a = 0, T* b = 0 )
        : member_a(a), member_b(b), pointer_to_member(pm) {}

    T* get() { return this->*pointer_to_member ; }

    T* member_a ;
    T* member_b ;
    T* list::*pointer_to_member ;
    // ...
};

template < typename T > T* get_it( list<T>& lst )
{ return lst.*lst.pointer_to_member ; }

int main()
{
    int a = 11111, b = 22222 ;

    list<int> lst1( &list<int>::member_a, &a, &b ) ;
    list<int> lst2( &list<int>::member_b, &a, &b ) ;

    std::cout << *lst1.get() << '\t' << *get_it(lst1) << '\n'
              << *lst2.get() << '\t' << *get_it(lst2) << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

Are you looking for something like this?

template< typename T > struct list
{
    T* current ;
};

template< typename T, T* T::*PTRMEMBER >
T* get_next( list<T>& lst ) 
{ 
    lst.current = lst.current->*PTRMEMBER ; 
    return lst.current ;
}

struct A
{
    A* member_one ;
    A* member_two ;
};

int main()
{
    A one = A() ;
    A two = A() ;
    A three = { &two, &one } ;
    A four = { &three, &two } ;

    list<A> lst = { &four };

    std::cout << get_next< A, &A::member_one >( lst ) 
              << '\t' << &three << '\n' ;

    std::cout << get_next< A, &A::member_two >( lst ) 
              << '\t' << &one << '\n' ;
}
vijayan121 1,152 Posting Virtuoso

Couple of general points: In general use references (instead of pointers) for strings, streams and the like. Use const where ever and whenever possible - it is your friend. Prefer using '\n' to std::endl to send a new line to a stream, unless your intent is to also flush the stream (performance).

Now, re. the code to read and write strings using binary i/o:

To get the number of characters in a string use the size() method. As you are dealing with binary stuff, c_str() is a null terminated string; it will mess you up if the string itself contains null characters.

Use the result of c_str() only immediately after calling it; it cannot be safely used once the string is modified.

The modified code would be something like:

// Writes a string outStr to BIN file ofs
void stringToBINFile( const string& outStr, ostream& os )
{
    int n_chars = outStr.size() ; //Length has to be known when reading
    os.write((char *)&n_chars, sizeof(n_chars));
    if( n_chars > 0 ) os.write( (const char *)&*outStr.begin(), n_chars );
}

// Reads a string inStr from a BIN file ifs
void stringFromBINFile( string& inStr, istream& is )
{
    int n_chars;
    is.read((char *)&n_chars, sizeof(n_chars));
    if( n_chars > 0 )
    {
        inStr = string( n_chars, ' ' ) ;
        is.read( (char *)&*inStr.begin(), n_chars ) ;
    }
    else inStr = "" ;
}

void myWrite( const char* path, const string& outStr)
{
    ofstream ofs (path, ios::binary);
    stringToBINFile(outStr, ofs);
}

void myRead( const char* path, …
vijayan121 1,152 Posting Virtuoso

Use something like std::vector< boost::any >
http://www.boost.org/doc/libs/1_37_0/doc/html/any.html

vijayan121 1,152 Posting Virtuoso

Rewrite void Matrix::Multiply(Matrix b) ; as Matrix Matrix::Multiply( const Matrix& b ) const ; In the implementation, do not modify either of the two Matrix objects involved in the multiply. Construct a new result Matrix object of the appropriate size, populate it and return it.

Ok, I see that Dragon has preempted me.

mrnutty commented: Was thinking the same thing +4
vijayan121 1,152 Posting Virtuoso

> obj.baseInfo::SlotCount[0] = 5;
> This compiles fun but gives me an error after running it.

It should not compile (though IIRC, microsoft compilers just give a warning that memory would be corrupted and proceed to generate incorrect code that will corrupt the memory - on the stack in this case).

The name of a nested class is local to its enclosing class. To use the name of the nested class outside the enclosing class, qualify it with the name of the enclosing class.

int main()
{

	base obj;
	//obj.baseInfo::SlotCount[0] = 5; // error

	base::baseInfo info_object ;
        info_object.SlotCount[0] = 5 ; // fine

}

Also, declare the constructor as inline if you are going to define it in the header file. Else, you will get a linker error (constructor is multiply defined) if you #include the header in more than one translation unit.

You may also want to search this forum to discover the implications of using system("PAUSE"); in your code.

vijayan121 1,152 Posting Virtuoso

Yes, both Java and C++ support handling of errors by using exceptions, both have keywords throw, try and catch which behave similarly. But this similarity is deceptive, the philosophy behind the exception mechanism is fundamentally different in the two languages.

The Java mechanism requires you to deal with potential errors at the specific places that they might occur. You accomplish this with try...finally blocks; if you open a file, you wrap that and the code that follows in a try...finally construct and close the file in the finally block. Not too bad, but you have to recognize when you need to do it and consciously put it in place. Not fundamentally different from the C technique of checking a return value or a global errno and clean up in the face of errors at or near the point where the error occurred.

It is telling that C++ has no finally. It has something far slicker — RAII (Resource Acquisition Is Initialization). Essentially you use objects that encapsulate resources which have destructors that do the clean up for you if things go wrong. One example of this is the iostream library. fstreambuff destructors release the memory for the file buffer, and fstream destructors close the file. Say, you create a file stream, and open a file for output, and an exception is thrown, the file is automatically closed during the stack unwind. Without the programmer having to do anything special or write any extra code.

void some_function( object …
vijayan121 1,152 Posting Virtuoso

In this specific case (file not found), the what() of the exception may make sense to the user. But more often, for instance, if a std::vector<> throws a std::out_of_range, it is meaningful only to to the code (programmer) and not to the end-user.

It is never a good idea to create your own exception classes which are not related to the <stdexcept> heirarchy. Standard exceptions like std::bad_aloc, std::bad_cast and std::bad_exception are thrown by the implementation and the standard library components throw exceptions like std::out_of_range. It makes error handling easier if you do not have to have two separate catch expressions every time; a single catch( const std::runtime_error& ) should be able to catch all run time errors.

There are two ways to address your specific problem.

The first, and much simpler one (which I prefer) is to right a function to convert the what() of an exception to a wide character string.

std::wstring what2wstr( const std::exception& ex )
{
    // convert ex.what() to a wide character string and return it
    // trivially done here, ok for US-ASCII in UTF-8 => UNICODE
    std::string str( ex.what() ) ;
    std::wstring wstr( str.size(), ' ' ) ;
    std::copy( str.begin(), str.end(), wstr.begin() ) ;
    return wstr ;
}

The second is to create an exception base class with a wwhat() that returns a wide character string, and then multiply inherit your exceptions from this and one of the standard exception classes.

struct wchar_exception
{
    virtual const wchar_t* wwhat() const { …
vijayan121 1,152 Posting Virtuoso

In general, if you're displaying error messages to the user based on what() of an exception that was thrown, you are probably doing something wrong.

The code that throws an exception is very unlikely to be able to compose a relevant and user-comprehensible error message at the point an exception is thrown. Exceptions are for communicating errors between sections of code and are not designed to be for user-consumption. They are not designed to be localizable (why would they be? An exception could be thrown by code very far away from the user). The code that catches the exception should inspect it to find out what it is about, and display the error message accordingly.

You can always define your own class derived from std::exception which stores std::wstring inside it, and use that for all your exceptions. But it would perhaps be the wrong error handling idiom to use.

The Boost error handling guidelines covers this aspect well:

Don't worry too much about the what() message. It's nice to have a message that a programmer stands a chance of figuring out, but you're very unlikely to be able to compose a relevant and user-comprehensible error message at the point an exception is thrown. Certainly, internationalization is beyond the scope of the exception class author. Peter Dimov makes an excellent argument that the proper use of a what() string is to serve as a key into a table of error message formatters.

from http://www.boost.org/community/error_handling.html

vijayan121 1,152 Posting Virtuoso

> declare it as private and just leave an empty implementation?
ideally, declare it as private and do not define it.

> Is this common/useful?
useful, yes. common, not all that much.
if there is a class that you write (for example a window), and want its instances not to have value semantics, you need to suppress any compiler-generated copy constructor and assignment operators.

struct window
{
    // ...
    private:
       window( const window& ) ; // do not define this
       void operator= ( const window& ) ; // do not define this
    // ...
}

see: http://www.boost.org/doc/libs/1_37_0/libs/utility/utility.htm#Class_noncopyable

skatamatic commented: To the point and accurate +3
vijayan121 1,152 Posting Virtuoso
template <typename C>
typename C::iterator SlowFind(C& c, const typename C::value_type& v)
{
    typename C::iterator i;
    for (i = c.begin(); i != c.end() && *i != v; ++i)
        ;
    return i;
}

this is broken when C is a const container.
c.begin() and c.end() returns objects of type C::const_iterator.

in C++98 you would have to do something like

template < typename CNTR > struct container_traits
{  typedef typename CNTR::iterator iterator ;  } ;

template < typename CNTR > struct container_traits< const CNTR >
{ typedef typename CNTR::const_iterator iterator ; } ;

template < typename CNTR >
typename container_traits<CNTR>::iterator SlowFind( CNTR& cntr, 
                                const typename CNTR::value_type& value )
{   return std::find( cntr.begin(), cntr.end(), value )  ;  }

C++09 makes it a lot easier:

template < typename CNTR >
auto SlowFind( CNTR& cntr, const typename CNTR::value_type& value 
             ) -> decltype( cntr.begin() ) 
{   return std::find( cntr.begin(), cntr.end(), value )  ;  }
vijayan121 1,152 Posting Virtuoso

this is nothing specific to constructors or passing parameters to functions.
it is just the application of the C++ rules for resolving a call to an overloaded function.

#include <iostream>

void foobar( int& arg )
{ std::cout << "foobar( int& )\n" ; }

void foobar( const int& arg )
{ std::cout << "foobar( const int& )\n" ; }

int main()
{
  int i = 7 ;

  foobar(i) ; // foobar( int& arg ) : exact match
  // foobar( const int& ) : conversion from int& to const int&
  // exact match preferred over conversion

  const int j = 7 ;
  foobar(j) ; // foobar( const int& arg ) : exact match
  // foobar( int& arg ) can't be called at all ( no conversion )

}

in your snippet:

int main ()
{
  MyClass f(4);
  Func (f); // make copy of object f. f is a modifiable lvalue
  // overload resolves to exact match : MyClass::MyClass( MyClass& )
  
  const MyClass& g = f ;
  Func (g); // make copy of object g. g is not a modifiable lvalue
  // call MyClass::MyClass( const MyClass& ) to make the copy
}

the copy constructor that takes a non-const object as argument is used to make copies of non-const objects.
and the copy constructor that takes a const object as argument is used to make copies of const objects.

vijayan121 1,152 Posting Virtuoso

you can answer this yourself if you write a small test program and run it. for example:

#include <iostream>

struct A
{
  A() { std::cout << "A::default constructor\n" ; }
  A( const A& ) { std::cout << "A::copy constructor\n" ; }
  A& operator= ( const A& )
  { std::cout << "A::assignment\n" ; return *this ; }
};

struct B { A a[2] ; };

int main()
{
  B one ;
  std::cout << "-----------\n" ;
  B two(one) ;
  std::cout << "-----------\n" ;
  one = two ;
}
vijayan121 1,152 Posting Virtuoso

> Does it make sense to write a virtual method in the templated base class
> in order to force derived classes to have an appropriate addelement() method?
no. the polymorphism provided by templates is compile-time polymorphism; if you need an addelement() in a class and the class does not provide it, it will be caught at compile-time.

> first method would lead to a maintenance nightmare;
> as more chart types are added, more overloaded addelement() placeholders need to be added
true.

vijayan121 1,152 Posting Virtuoso

if you absolutely need a base class Chart (with virtual functions), a hack would be to overload the AddElement function.

i would prefer using templates for your containers as suggested by Narue in the other thread. and as for this issue:
> ... generic template<class T> container and have a method addelement(T& elt)
> but the implemebtation of addelement() depends on the element being added
template specialization would address the problem.

#include <stdexcept>

struct DataElement { /* ... */ };
struct AverageElement { /* ... */ };

#ifdef INHERIT

struct Chart // base class
{
  virtual void AddElement( const DataElement& ) = 0 ;
  virtual void AddElement( const AverageElement& ) = 0 ;
  // other (pure) virtual functions
};

struct DataChart : Chart
{
  virtual void AddElement( const DataElement& )
  { /* add DataElement */ }

  virtual void AddElement( const AverageElement& )
  { throw std::logic_error("incorrect element type") ; }
  
  // other overrides etc.
};

struct AveragesChart : Chart
{
  virtual void AddElement( const DataElement& )
  { throw std::logic_error("incorrect element type") ; }

  virtual void AddElement( const AverageElement& )
  { /* add AverageElement */ }
   
  // other overrides etc.
};

#else // GENERIC

template< typename T > struct chart_base
{
  // common stuff goes here
};

template< typename T > struct chart ; // generalization

// specialization
template<> struct chart<DataElement> : chart_base<DataElement> 
{
  void addelement( const DataElement& ) ;
  // other DataChart specific stuff
};

// specialization
template<> struct chart<AverageElement> : chart_base<AverageElement>
{
  void AddElement( const …
vijayan121 1,152 Posting Virtuoso

> Is there any real different between using an union between two types and a reinterpret_cast between two types
yes, there are quite a lot of differences.
a union reinterprets the layout of memory (depending on which member is accessed).
a reinterpret_cast is a conversion operator.

the conversions that can be performed using a reinterpret_cast are limited; the permissible ones are specified by the standard.

IS 5.2.10 - Reinterpret cast

-1- The result of the expression reinterpret_cast<T>(v) is the result of converting the expression v to type T.
...
Conversions that can be performed explicitly using reinterpret_cast are listed below. No other conversion can be performed explicitly using reinterpret_cast.
-2- The reinterpret_cast operator shall not cast away constness. ...
-3- The mapping performed by reinterpret_cast is implementation-defined. ...

and then it goes on to list the conversions that can be performed explicitly using reinterpret_cast. for example this is what is specified about pointer to integral and integral to pointer conversions:

-4- A pointer can be explicitly converted to any integral type large enough to hold it. The mapping function is implementation-defined.
[Note: it is intended to be unsurprising to those who know the addressing structure of the underlying machine. ]
-5- A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type …

Alex Edwards commented: Thanks for the elaborate explanation! +3
vijayan121 1,152 Posting Virtuoso

the typical work around (as exemplified by the standard library containers and function objects) is to have the generic type announce dependent types via suitable typedefs.

#include <vector>
#include <iostream>
#include <typeinfo>

template <class T>
class CObject
{
  public:
    typedef T numeric_type ;
    typedef std::vector<T>* output_type ;

    inline virtual ~CObject () { }
    virtual output_type Output( const std::vector<int>* Input ) = 0 ;
};

template< typename T >
typename T::output_type function( T& object,
                                  const std::vector<int>* input )
{
  typedef typename T::output_type result_type ;
  std::cout << "result type is " << typeid(result_type).name() << '\n' ;
  result_type result = object.Output( input ) ;
  return result ;
}
vijayan121 1,152 Posting Virtuoso

simulating long division by hand (shift and subtract):
http://courses.cs.vt.edu/~cs1104/Division/ShiftSubtract/Shift.Subtract.html

vijayan121 1,152 Posting Virtuoso

> The structs are padded so that no padding occurs when we create an array of them,
> like with a scalar variable because if the compiler padded the struct when it created the
> array it wouldn't be the same behaviour we have when we created an array of integers.
> Is this notion correct?

not merely 'it wouldn't be the same behaviour we have when we created an array of integers'. array subscript and pointer arithmetic would not work otherwise.

> an anyone put it more formally?

the formal exposition is in the legalese in the IS (ISO/IEC 14882).
but this arises out of a few simple requirements:
1. the layout and sizeof an object of a particular compile-time type should be known at compile-time.
2. these have to be independent of the storage duration of the object.
3. these also have to be independent of whether the object is an element of an array, a member of a class, a base class sub-object etc.
4. object types can have alignment requirements.
5. an object should be allocated at an address that meets the alignment requirements of its object type.
6. array subscript and pointer arithmetic should work correctly.
7. the memory model of C++ should be compatible with that of C89.

here is a (poor) attempt at a formal explanation:

struct A
{
   char a ;
   int b ;
   char c …
vijayan121 1,152 Posting Virtuoso
struct align1
{
	double a;
	char b;
	int c;
	short d;
};

> why the compiler pads the structure in the end?

hint:
1. does the struct align1 have an alignment requirement?
2. if we create an array align1 array[5] ; would the alignment be right for every element in the array?

vijayan121 1,152 Posting Virtuoso
#include <iostream>
#include <limits>

// addition can be done using bitwise xor
// with adjustments for carry bits
unsigned int plus( unsigned int first, unsigned int second )
{
  unsigned int carry = first & second ; // the carry bits
  unsigned int result = first ^ second ; // the result bits

  while( carry ) // loop over the carry bits
  {
    carry <<= 1U ; // shift carry to next bit
    unsigned int temp = result ^ carry ;
    carry &= result ;
    result = temp ;
  }

  return result;
}

// to subtract, add the two's complement
unsigned int minus( unsigned int first, unsigned int second )
{
  unsigned int carry = ~second & 1U ;
  unsigned int twos_complement = ~second ^ 1U ;

  while( carry )
  {
    carry <<= 1U ;
    unsigned int temp = twos_complement ^ carry ;
    carry &= twos_complement ;
    twos_complement = temp;
  }

  return plus( first, twos_complement ) ;
}

int main()
{
  enum { RADIX = std::numeric_limits<unsigned int>::radix } ;
  struct check_it { char static_assert[ RADIX == 2 ? 1 : -1 ] ; } ;

  for( int i=0 ; i<10 ; ++i )
  {
    unsigned int a = std::rand()%1000 ;
    // a*7 === ( a*8 - a ) === ( a*4 + a*2 + a )
    std::cout << a << " * 7  = " << minus( a<<3U, a ) << " ("
       << plus( a<<2U, plus( a<<1U, a ) ) << ") (" << a*7 << ")\n" ;
  }
}
Alex Edwards commented: You've got quite a head on your shoulders =P +1
vijayan121 1,152 Posting Virtuoso

n is made automatically from n.o by running the linker (usually called ld) via the C compiler. The precise command used is ...

This rule does the right thing for a simple program with only one source file. It will also do the right thing if there are multiple object files (presumably coming from various other source files), one of which has a name matching that of the executable file....

In more complicated cases, such as when there is no object file whose name derives from the executable file name, you must write an explicit command for linking.

from http://www.gnu.org/software/make/manual/make.html#Implicit-Rules

vijayan121 1,152 Posting Virtuoso

> If you're never going to use a custom allocator, it doesn't make any sense to do that extra work.
the fundamental problem with your code is not that it does not cater for a custom allocator for the container. it is that it does not compile.

vijayan121 1,152 Posting Virtuoso

> typename is not followed by a name, which I find confusing
since the intent is to declare a template template type (ttp), the identifier following typename is just a place-holder (like the name of a formal parameter to a function) and can be omitted.
http://www.comeaucomputing.com/techtalk/templates/#ttp

a standard container has *two* template parameters; the value_type and the allocator_type.
the function should be:

template< typename T, typename A, template
          <typename VALUE_TYPE,typename ALLOCATOR_TYPE> class Container >
int my_func( std::map<T, Container<T,A> >& arg ) 
{
  typedef std::map< T, Container<T,A> > Map;
  typedef typename Map::iterator Iter;
  typedef typename Container<T,A>::iterator CIter;

  int count = 0;
  // ...
  return count;
}
vijayan121 1,152 Posting Virtuoso

> So I could write something like this:
...
no, you can't. you need to write something like:

std::size_t max = 0; // Number set by user at execution
// ...
long (*pBigArray)[100][100] = new long [max][100][100];

> Can someone tell me why I can't write the above?
for performing pointer arithmetic (including array subscrpt) correctly, the compiler needs to know (at compile time) the size of the element that is pointed to.

> Is there a way to get around this?
the simplest would be to use std::vector

vijayan121 1,152 Posting Virtuoso

> ...maybe the array is automatically cleared from memory when the application closes...

right, provided your program is running under an os ( like unix, windows, linux ... ) which gives a separate virtual address space for each process. when a process terminates, all the resources it owns are reclaimed by the system; and its private memory would be deallocated.

vijayan121 1,152 Posting Virtuoso
case 1 : float hipvalley(); // this is the Hip/Valley choice.

that is merely a declaration of the function hipvalley.
to invoke the function (and ignore its result), write

case '1' : hipvalley(); // this is the Hip/Valley choice.
vijayan121 1,152 Posting Virtuoso
#include <cstdlib>
#include <string>

inline char random_digit() { return '0' + std::rand() % 10 ; }

inline std::string random_pin( std::size_t ndigits )
{
  std::string pin ;
  for( std::size_t i = 0 ; i < ndigits ; ++i ) pin += random_digit() ;
  return pin ;
}
vijayan121 1,152 Posting Virtuoso

or

// ...
int Strength = 5 ;
int Intelligence = 2 ;
int Agility = 3 ;
int Defense = 3 ;
int Health = 10 ;
int Level = 1 ;

for(;;)
{
  char classChoice ;
  cin >> classChoice ;

  if( classChoice=='W' || classChoice=='w' )
  {
    break ;
  }
  else if( classChoice=='M' || classChoice=='m' )
  {
    Strength = 2 ;
    Intelligence = 5 ;
    Defense = 2 ;
    break;
  }
  else
  {
    cerr << "You did not enter a legal value.\n";
  }
}

Character player( Strength, Intelligence, Agility,
                  Defense, Health, Level ) ;
player.DisplayStats() ;
// ...
vijayan121 1,152 Posting Virtuoso

> ...139 files, with 16,000 lines of code...
> ...So how do I start to disect messy code that is not documented and not written by me?
> How does somebody look at code and start to make sense of it?

ok. so you have about 70 components or so. each with a header and a .cc average of about 200+ lines of code per component. (could have been a lot worse; imagine your plight with 16 components with about 1000 lines of code per component).

you could start by making a dependency graph of these components. compile a component a.cc with a -MMD switch to get a.d which lists its dependecies. compile all components this way and prepare the dependency graph out of information in the .d files.

now, scan through components which are at the lowest level in the dependency graph (those that have no other dependencies) to get an overall idea of what they do. and move up level by level in the dependency hierarchy to see what the high level architecture is.

then, determine where the component you are going to write fits in in this hierarchy and focus on the sub-graph that involves this component.

vijayan121 1,152 Posting Virtuoso

> 3.6 * vector_a; why can I not implement this binary operator as a member operator of a class Vector?
you can, if the class Vector is your own class.
if not ( for example for standard containers ), you can overload this operator as a free function (not a member function). eg.

#include <vector>
#include <algorithm>
#include <functional>
#include <iterator>

template < typename T, typename A,
           template< typename U, typename V > class container >
container<T,A> operator* ( const T& n,
                           const container<T,A>& cntr )
{
  container<T,A> result ;
  std::transform( cntr.begin(), cntr.end(),
                  std::back_inserter(result),
                  std::bind1st( std::multiplies<T>(), n ) ) ;
  return result ;
}

template < typename T, typename A,
           template< typename U, typename V > class container >
inline container<T,A> operator* ( const container<T,A>& cntr,
                                  const T& n )
{ return n * cntr ; }

int main()
{
  std::vector<double> v1(10,3.4) ;
  std::vector<double> v2 = 3.6 * v1 ;
}

> If I want pedal to be a pure virtual function, how do I do that?
put an = 0 ; at the end of the function declaration. and not in the definition (if you want to define it; it need not be defined).

> but virtuals have me kind of lost virtual means: the function is to be called based on the run-time type of the object, not the compile-time type of the variable. eg.

#include <iostream>
#include <typeinfo>

struct base_class
{
  virtual void virtual_foo() = 0 ; // pure

  void nonvirtual_bar() …
vijayan121 1,152 Posting Virtuoso

sortValues is not a template member. you need to modify DO_SORT

#define DO_SORT(varName, a, b, c, d) (*(varName)).sortValues(a, b, c, d)

when you are sorting an array of char , use MySort<char> not MySort<char*>

//...
    MySort<char> *myCharSorter = new MySort<char>();
    DO_SORT(myCharSorter, charPt, 0, 5, sortFunction);
//...

using all these void* (java object?), preprocessor macros and non-standard extensions (__typeof__) is not good C++.
here is your program translated into C++ (with a minor bug fixed).

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

template<class T>
class MySort
{
      private:

      public:
             MySort(){};
             ~MySort(){};
             void sortValues( T* value, int start, int size,
                              void (*functocall)(T*, T*));
             //This method accepts a user-defined function and sorts the value.
             //The pointer is expected to have more than just one value, so it will be an array of some type.

              bool isSorted( const T* value, int start, int size)
              {
                   for(int i = start; i < size-1 ; i++)
                   {
                        if(value[i] > value[i + 1])
                           return false;
                   }

                   return true;
              };
};

template<class T>
void MySort<T>::sortValues( T* value, int start, int size,
                            void (*functocall)(T*, T*))
{
    if(start < size)
    {
       while(!isSorted(value, start, size))
       {
            for(int i = start; i < size-1 ; i++)
            {
               T *left = value+i, *right = value+i+1 ;
               (*functocall)((left), (right));
            }
       }
    }
    else
       std::cerr << "Start point cannot be greater than the size!" ;
}

template< typename T > void sortFunction( T* arg1, T* arg2 )
{
  if( *arg2 < *arg1 )
  {
    T temp = *arg1 …
Salem commented: Much better :) +17
vijayan121 1,152 Posting Virtuoso
for( int i=0 ; i<10 ; ++i )
    numb2[i] = i%2 == 0 ? (i/2)*5 : i ;
vijayan121 1,152 Posting Virtuoso

> an algorithm better than FFT for getting large numbers(of the order of 10 power 30 or more)?
FFT multiplications are efficient when numbers are very large. the other popular multiplication algorithms are Karatsuba and Toom-3. http://gmplib.org/manual/Multiplication-Algorithms.html#Multiplication-Algorithms

in general Karatsuba is suitable for smaller numbers, Toom-3 for larger numbers and FFT for very large numbers. which is the most appropriate for a particular number depends on the processor.
for example, for a x86/pentium4/sse2 processor, GMP has determined the following thresholds for multiplication (in number of limbs: 32-bits per limb on this processor)
Karatsuba 18 limbs
Toom-3 139 limbs
FFT MODF 456 limbs
FFT 5888 limbs
from gmp-4.1.4/mpn/x86/pentium4/sse2/gmp-mparam.h
http://www.srcdoc.com/gmp_4.1.4/

vijayan121 1,152 Posting Virtuoso

> i try to avoid copying anything than 2 pointers...
swapping pointers is easy; swap pointers to arrays just like you swap any other pointers.

#include <stdio.h>

void swap( int rows, int cols, float (**after)[rows][cols] , 
           float (**before)[rows][cols] )
{
  float (*temp)[rows][cols] = *after ;
  *after = *before ;
  *before = temp ;
}

int main()
{
  int rows = 3, cols = 4 ;
  float one[rows][cols] ; one[0][0] = 1.1 ;
  float two[rows][cols] ; two[0][0] = 2.2 ;
  float (*p1)[rows][cols] = &one ; 
  float (*p2)[rows][cols] = &two ; 
  printf( "%f\t%f\n", (*p1)[0][0], (*p2)[0][0] ) ; 
  swap( rows, cols, &p1, &p2 ) ;
  printf( "%f\t%f\n", (*p1)[0][0], (*p2)[0][0] ) ; 
}

this means that you will have to write the array_function in terms of pointers to arrays:

void array_function( int rows, int cols, float (*after)[rows][cols],
                     float (*before)[rows][cols] )
{
	//for some iterations	
	for(;;)
	{
		int i, j ;
		//for all the elements int the array
		for (i=1; i<rows; i++)
			for(j=1; j<cols; j++)
				(*after)[i][j] = 4 * (*before)[i][j] ;

		//afterwards prepare for the next iteration
		swap( rows, cols, &after, &before ) ;
	}
}
n.aggel commented: always helpful! +2
vijayan121 1,152 Posting Virtuoso

> maybe the book Java Concurrency in Practice addresses this thing
no, it doesn't. it is a good book on concurrency issues in general, but discusses only java.

> where do you stand vijayan121
closer to Knuth than to Sutter. my experience has been that the extra synchronization overhead very often cancels out quite a bit of the performance gains. not to mention exponentially greater complexity of the software. it is much cheaper to just buy more machines than hire more (good) programmers.

> But how you would solve others like i.e examining a 2d matrix?
high performance mathematical/graphics/engineering computing would remain a niche area. again, i tend to agree with Knuth:

I know that important applications for parallelism exist—rendering graphics, breaking codes, scanning images, simulating physical and biological processes, etc. But all these applications require dedicated code and special-purpose techniques, which will need to be changed substantially every few years.

> can you point to any articles concerning the concurrency in the kernel?
freebsd:
not too many articles exist. to be current, you need to look at the source code. and the freebsd-hackers mailing list. http://lists.freebsd.org/mailman/listinfo/freebsd-hackers
a somewhat dated reference is the book 'The Design and Implementation of the FreeBSD Operating System' http://www.informit.com/store/product.aspx?isbn=0201702452
some other documents/papers that i'm aware of:
http://people.freebsd.org/~kris/scaling/7.0%20Preview.pdf
http://www.onlamp.com/pub/a/bsd/2008/02/26/whats-new-in-freebsd-70.html?page=4
http://ieeexplore.ieee.org/Xplore/login.jsp?url=/iel5/4215472/4215473/04215520.pdf
http://portal.acm.org/citation.cfm?id=1251976.1252627&coll=GUIDE&dl=GUIDE
http://www.watson.org/~robert/freebsd/2005eurobsdcon/eurobsdcon2005-netperf.pdf

solaris:
book: 'Solaris Internals: Solaris 10 and OpenSolaris Kernel …

vijayan121 1,152 Posting Virtuoso

> is there any way to use threads in c++

the ISO standards committee (c++09) has voted voted in a number of concurrency extensions into the working draft (memory model, atomics library, basic threads, locks, and condition variables). an asynchronous future<T> type would be added later, but features like thread pools are deferred.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2320.html

the Boost.Thread library has been rewritten to align with c++09 proposals.
http://www.boost.org/doc/libs/1_35_0/doc/html/thread.html

> Is it common for "everyday" applications (in todays multicore platforms) to use threads?

in windows, probably yes. threads have been widely used over the years.
in unix, probably no. fork is very efficient.
most of the push towards concurrency seems to be in the kernel (solaris, bsd), filesystems (zfs) and libc ( bsd's gemalloc, google's tcmalloc) right now.

opinion seems to be divided; here are two extremes:

I won’t be surprised at all if the whole multithreading idea turns out to be a flop, worse than the "Itanium" approach that was supposed to be so terrific—until it turned out that the wished-for compilers were basically impossible to write.
Let me put it this way: During the past 50 years, I’ve written well over a thousand programs, many of which have substantial size. I can’t think of even five of those programs that would have been enhanced noticeably by parallelism or multithreading. - Donald Knuth

http://www.informit.com/articles/article.aspx?p=1193856

Concurrency is the next major revolution in how we write software
Applications …

vijayan121 1,152 Posting Virtuoso
for(it = aMap.begin(); it != aMap.end(); it++){
  //some processing
  if(//some condition){
    //some processing
    aMap.erase(key);
    // this is undefined behaviour
    // the iterator is invalid after the erase
    it--;
  }
}

this will work on conforming implementations:

it = aMap.begin() ;
while(  it != aMap.end() )
{
  //some processing
  if(some_condition)
  {
    //some processing
    aMap.erase( it++ ); // postfix required
    continue; // don't increment again
  }
  ++it ; // not erased, increment
}

note: with user defined types, prefer prefix increment/decrement over postfix.