Thread: Counter will not increment

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    73

    Counter will not increment

    Hello! In the code below, why does the counter not increment if I use Template arguments?

    Code:
    #include <iostream>
    
    using namespace std;
    
    struct parent
    {
    	int counter = 0;
    	parent() {};
    };
    
    struct child : parent
    {
    	child() {};
    };
    
    template <typename A, typename B>
    void f(A a, B b)
    {
    	b.counter += 1;
    	cout << b.counter << endl;
    }
    
    int main()
    {
    	child Anne;
    	child Pete;
    	
    	for (int i = 1; i <= 5; ++i)
    	{
    		f(Anne, Pete);
    		f(Pete, Anne);
    	}
    	return 0;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,013
    It does increment: you keep copying the objects from main and then increment the counter of the copy.

    Or, we can say that it doesn't increment the way you expected, and this has nothing to do with the use of templates: you merely forgot the basic rule about copying versus passing by reference.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Counter
    By jackirl in forum C++ Programming
    Replies: 5
    Last Post: 11-27-2011, 12:01 PM
  2. Post Increment an Pre Increment operators in c++
    By anil_ in forum C++ Programming
    Replies: 4
    Last Post: 11-12-2011, 08:27 PM
  3. Page File counter and Private Bytes Counter
    By George2 in forum Tech Board
    Replies: 0
    Last Post: 01-31-2008, 03:17 AM
  4. Post increment and pre increment help
    By noob2c in forum C++ Programming
    Replies: 5
    Last Post: 08-05-2003, 03:03 AM
  5. Help!Counter...
    By Unregistered in forum C++ Programming
    Replies: 4
    Last Post: 05-25-2002, 01:14 AM

Tags for this Thread