Author Topic: Using C code in a C++ program ...  (Read 37683 times)

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
Using C code in a C++ program ...
« on: July 18, 2013, 09:43:10 AM »
Why would any one ever want to use C code in a C++ program?



Here are some typical 'student reasons' why ...


1.  The prof said to...

2.  You want faster code by using C strings...

3.  You want your executable file size to be much reduced...
« Last Edit: July 18, 2013, 12:33:23 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
Re: Using C code in a C++ program ...
« Reply #1 on: July 18, 2013, 09:50:57 AM »
This next series of 4 programs demonstrates prototyping the program ... firstly all in C++ code style ...

then ... stepwise ... converting certain parts to C code

Note how much smaller the compiled final version is ...

that uses all dynamic C strings, a dynamic array, and printf ...

instead of C++ string, STL vector, and cout

Step 1.  using C++ string and the STL vector ...

Code: [Select]
// test_class_Team_step1.cpp //

// step 1 to solution:
// proto-type using ALL C++ string and STL vector



#include <iostream>
#include <iomanip> // re. setw
#include <string>
#include <vector>


//using namespace std;

class Player
{
    std::string name;
    int id;
public:
    // default and value ctor...
    Player( std::string n = "", int i = 0 ) : name(n), id(i) {}
    void print() const
    {
        std::cout << "ID: " << std::setw(3) << id
                  << ",  Name: " << name;
    }
} ;


class Team
{
    std::vector< Player > players;
    std::string tName;
public:
    // default ctor ...
    Team() {}
   
    void set_tName( std::string tN ) { tName = tN; }
   
    void push_back( const Player& pl )
    {
        players.push_back( pl );
    }
   
    void print() const
    {
        for( size_t i = 0; i < players.size(); ++ i )
        {
            players[i].print();
            std:: cout << "\n";
        }
        std::cout << "Team \"" << tName << "\" has "
                  << players.size() << " players.\n";
    }
} ;

   

//My main function looks like this:
int main()
{
    using std::string;
   
    const string names[] = { "Brad Shaw", "Aimen Adams", "Sal Dimitry",
                           "Cristi Anreaz", "Poala James" };
    const int ids[] = { 232, 444, 135, 52, 134 };
    const int size = sizeof(ids) / sizeof(int);
   
    const string tName = "Toronto Maple Leafs";
   
    Team myTeam; // calls default ctor
   
    // get some players in the team
    for( int i = 0; i < size; ++ i  )
         myTeam.push_back( Player( names[i], ids[i] ) );
   
    myTeam.set_tName( tName );
   
    myTeam.print();
}
« Last Edit: July 18, 2013, 12:33:55 PM by David »

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
Re: Using C code in a C++ program ...
« Reply #2 on: July 18, 2013, 09:53:38 AM »
Step 2.

Code: [Select]
// test_class_Team_step2.cpp //

// here ... using ALL dynamic C strings and STL vector


#include <iostream>
#include <iomanip> // re. setw
//#include <string>
#include <vector>

#include <cstring> // re. strlen, strcpy



class MyString
{
    char* str;
    friend std::ostream& operator << ( std::ostream& os, const MyString& ms )
    {
        return os << ms.str;
    }
public:
    MyString( const char* s = "" )
    {
        str = new char[strlen(s)+1];
        strcpy( str, s );
    }
    ~MyString() {  delete [] str; }
    MyString( const MyString& ms )
    {
        str = new char[strlen(ms.str)+1];
        strcpy( str, ms.str );
    }
    MyString& operator = ( const MyString& ms )
    {
        if( this != &ms )
        {
            delete [] str;
            str = new char[strlen(ms.str)+1];
            strcpy( str, ms.str );
        }
        return *this;
    }
} ;


class Player
{
    MyString name;
    int id;
public:
    // default and value ctor...
    Player( MyString n = "", int i = 0 ) : name(n), id(i) {}
    void print() const
    {
        std::cout << "ID: " << std::setw(3) << id
                  << ",  Name: " << name;
    }
} ;


class Team
{
    std::vector< Player > players;
    MyString tName;
public:
    // default ctor ...
    Team() {}

    void set_tName( MyString tN ) { tName = tN; }

    void push_back( const Player& pl )
    {
        players.push_back( pl );
    }

    void print() const
    {
        for( size_t i = 0; i < players.size(); ++ i )
        {
            players[i].print();
            std:: cout << "\n";
        }
        std::cout << "Team \"" << tName << "\" has "
                  << players.size() << " players.\n";
    }
} ;



//My main function looks like this:
int main()
{

    const char* names[] = { "Brad Shaw", "Aimen Adams", "Sal Dimitry",
                           "Cristi Anreaz", "Poala James" };
    const int ids[] = { 232, 444, 135, 52, 134 };
    const int size = sizeof(ids) / sizeof(int);

    const char* tName = "Toronto Maple Leafs";

    Team myTeam; // calls default ctor

    // get some players in the team
    for( int i = 0; i < size; ++ i  )
         myTeam.push_back( Player( names[i], ids[i] ) );

    myTeam.set_tName( tName );

    myTeam.print();
}

Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
Re: Using C code in a C++ program ...
« Reply #3 on: July 18, 2013, 09:54:51 AM »
Step 3.


Code: [Select]
// test_class_Team_step3.cpp //

// here ... using ALL dynamic C strings
// AND a dynamic array


#include <iostream>
#include <iomanip> // re. setw
//#include <string>
//#include <vector>

#include <cstring> // re. strlen, strcpy



class MyString
{
public:
    MyString( const char* s = "" ) // default and value ctors...
    {
        str = new char[strlen(s)+1];
        strcpy( str, s );
    }
    ~MyString() { delete [] str; } // dtor
    MyString( const MyString& ms ) // copy ctor
    {
        str = new char[strlen(ms.str)+1];
        strcpy( str, ms.str );
    }
    MyString& operator = ( const MyString& ms ) // overloaded =
    {
        if( this != &ms )
        {
            delete [] str;
            str = new char[strlen(ms.str)+1];
            strcpy( str, ms.str );
        }
        return *this;
    }
private:
    char* str;
    friend std::ostream& operator << ( std::ostream& os, const MyString& ms )
    {
        return os << ms.str;
    }
} ;


class Player
{
public:
    // default and value ctor...
    Player( MyString n = "", int i = 0 ) : name(n), id(i) {}
    void print() const
    {
        std::cout << "ID: " << std::setw(3) << id
                  << ",  Name: " << name;
    }
private:
    MyString name;
    int id;
} ;


class Team
{
public:
    // default ctor ...
    Team() : players(0), t_capacity(0), t_size(0) {}
   
    ~Team() { delete [] players; } // dtor
    Team ( const Team& tm ) // copy ctor
    {
        t_capacity = tm.t_capacity;
        t_size = tm.t_size;
        players = new Player[t_capacity];
        for( int i = 0; i < t_size; ++ i )
             players[i] = tm.players[i];
    }
    Team& operator = ( const Team& tm ) // overloaded =
    {
        if( this != &tm )
        {
            delete [] players;
            t_capacity = tm.t_capacity;
            t_size = tm.t_size;
            players = new Player[t_capacity];
            for( int i = 0; i < t_size; ++ i )
                 players[i] = tm.players[i];
        }
        return *this;
    }
   
    void set_tName( MyString tN ) { tName = tN; }
    //int size() const { return t_size; }
    //int capacity() const { return t_capacity; }

    void push_back( const Player& pl )
    {
        if( t_size == t_capacity ) enlarge();
       
        players[t_size] = pl;
        ++ t_size;
    }

    void print() const
    {
        for( int i = 0; i < t_size; ++ i )
        {
            players[i].print();
            std:: cout << "\n";
        }
        std::cout << "Team \"" << tName << "\" has "
                  << t_size << " players.\n";
    }
private:
    Player* players;
    int t_capacity;
    int t_size;
    MyString tName;
   
    void enlarge()
    {
        if( t_capacity != 0 ) t_capacity += t_capacity; // double
        else t_capacity = initial_capacity;
       
        Player* old = players; // get copy of addrsss
        players = new Player[t_capacity];
        for( int i = 0; i < t_size; ++ i ) players[i] = old[i];
        delete [] old;
    }
   
    static const int initial_capacity = 2;
} ;



int main()
{

    const char* names[] = { "Brad Shaw", "Aimen Adams", "Sal Dimitry",
                           "Cristi Anreaz", "Poala James" };
    const int ids[] = { 232, 444, 135, 52, 134 };
    const int size = sizeof(ids) / sizeof(int);

    const char* tName = "Toronto Maple Leafs";

    Team myTeam; // calls default ctor

    // get some players in the team
    for( int i = 0; i < size; ++ i  )
         myTeam.push_back( Player( names[i], ids[i] ) );

    myTeam.set_tName( tName );

    myTeam.print();
}


Offline David

  • Hero Member
  • *****
  • Posts: 647
    • View Profile
Re: Using C code in a C++ program ...
« Reply #4 on: July 18, 2013, 09:56:13 AM »
Step 4.


Code: [Select]
// test_class_Team_step4.cpp //

// here ... using ALL dynamic C strings
// and dynamic array
// AND printf from <cstdio>


//#include <iostream>
//#include <iomanip> // re. setw
//#include <string>
//#include <vector>

#include <cstdio>
#include <cstring> // re. strlen, strcpy


class MyString
{
public:
    MyString( const char* s = "" ) // default and value ctors...
    {
        str = new char[strlen(s)+1];
        strcpy( str, s );
    }
    ~MyString() { delete [] str; } // dtor
    MyString( const MyString& ms ) // copy ctor
    {
        str = new char[strlen(ms.str)+1];
        strcpy( str, ms.str );
    }
    MyString& operator = ( const MyString& ms ) // overloaded =
    {
        if( this != &ms )
        {
            delete [] str;
            str = new char[strlen(ms.str)+1];
            strcpy( str, ms.str );
        }
        return *this;
    }
    char* get_str() const { return str; }
private:
    char* str;
} ;


class Player
{
public:
    // default and value ctor...
    Player( MyString n = "", int i = 0 ) : name(n), id(i) {}
    void print() const
    {
        printf( "ID: %3d, Name: %s", id, name.get_str() );
    }
private:
    MyString name;
    int id;
} ;


class Team
{
public:
    // default ctor ...
    Team() : players(0), t_capacity(0), t_size(0) {}
   
    ~Team() { delete [] players; } // dtor
    Team ( const Team& tm ) // copy ctor
    {
        t_capacity = tm.t_capacity;
        t_size = tm.t_size;
        players = new Player[t_capacity];
        for( int i = 0; i < t_size; ++ i )
             players[i] = tm.players[i];
    }
    Team& operator = ( const Team& tm ) // overloaded =
    {
        if( this != &tm )
        {
            delete [] players;
            t_capacity = tm.t_capacity;
            t_size = tm.t_size;
            players = new Player[t_capacity];
            for( int i = 0; i < t_size; ++ i )
                 players[i] = tm.players[i];
        }
        return *this;
    }
   
    void set_tName( MyString tN ) { tName = tN; }
    //int size() const { return t_size; } // not used here
    //int capacity() const { return t_capacity; } // not used here

    void push_back( const Player& pl )
    {
        if( t_size == t_capacity ) enlarge();
       
        players[t_size] = pl;
        ++ t_size;
    }

    void print() const
    {
        for( int i = 0; i < t_size; ++ i )
        {
            players[i].print();
            putchar( '\n' );
        }
        printf( "Team \"%s\" has %d players.\n", tName.get_str(), t_size );
    }
private:
    Player* players;
    int t_capacity;
    int t_size;
    MyString tName;
   
    void enlarge()
    {
        if( t_capacity != 0 ) t_capacity += t_capacity; // double
        else t_capacity = initial_capacity;
       
        Player* old = players; // get copy of addrsss
        players = new Player[t_capacity];
        for( int i = 0; i < t_size; ++ i ) players[i] = old[i];
        delete [] old;
    }
   
    static const int initial_capacity = 2;
} ;



int main()
{
    const char* names[] = { "Brad Shaw", "Aimen Adams", "Sal Dimitry",
                           "Cristi Anreaz", "Poala James" };
    const int ids[] = { 232, 444, 135, 52, 134 };
    const int size = sizeof(ids) / sizeof(int);

    const char* tName = "Toronto Maple Leafs";

    Team myTeam; // calls default ctor

    // get some players in the team
    for( int i = 0; i < size; ++ i  )
         myTeam.push_back( Player( names[i], ids[i] ) );

    myTeam.set_tName( tName );

    myTeam.print();
}