Sample code of c plus plus by using delay?
Unfortunately, there is no cross-platform method of forcing a delay. Microsoft uses the sleep function (with a 1 second resolution) while UNIX uses usleep (with 1 nanosecond resolution). However, neither method can be regarded as being accurate in a multi-processing environment -- both will sleep for "at least" the given time, but if the system is busy your application will continue to sleep until its next time-slice comes around.
Although usleep has a resolution of 1 nanosecond (1 billionth of a second), the system's frequency determines the actual resolution. For instance if your system has a frequency of 25 million ticks per second, your resolution is only 25 microseconds, so you cannot sleep for any less than that. Plus you have to add on the time it takes to make the call.
C++11 provides much better support for hi-resolution timers in the <chrono> header, so at least we now have a portable method of sleeping for a preset duration. However the duration is still "at least" -- background tasks can still prevent your program from waking up on time.
The following example demonstrates how to print the current time and how to put your program to sleep for a duration. Note that we still have no portable method of obtaining the current time in a thread-safe manner -- but the code includes a portable workaround.
#include<iostream> // std::cout, std::endl
#include<iomanip> // std::put_time
#include<sstream> // std::stringstream
#include<chrono> // std::chrono (C++11)
#include<thread> // std::this_thread (C++11)
namespace my_std
{
// std::localtime is not thread-safe but there is
// no portable alternative in the standard. Thus
// we must define our own standards...
tm localtime (const std::time_t& time)
{
std::tm snapshot;
#if (defined (WIN32) defined (_WIN32) defined (__WIN32__))
localtime_s (&snapshot, &time); // Microsoft-specific
#else
localtime_r (&time, &snapshot); // POSIX
#endif
return snapshot;
}
};
// Returns the current time and date as a string.
std::string current_time_and_date()
{
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
time_t as_time_t = std::chrono::system_clock::to_time_t (now);
std::stringstream ss;
ss << std::put_time (&my_std::localtime (as_time_t), "%Y-%m-%d %X");
return ss.str();
}
int main()
{
std::cout << "The current time is: " << current_time_and_date() << std::endl;
std::cout << "Taking a nap for half-a-second..." << std::endl;
std::this_thread::sleep_for (std::chrono::milliseconds (500)); // half-a-second
std::cout << "The current time is: " << current_time_and_date() << std::endl;
// 5-second ticker...
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
for (unsigned tick=0; tick<5; ++tick)
{
std::this_thread::sleep_until (now + std::chrono::seconds (tick));
std::cout << "Tick..." << std::endl;
}
std::this_thread::sleep_until (
now + std::chrono::seconds (5));
std::cout << "BOOM!" << std::endl;
}
To make an object's members persistent, you must serialise the object. That is, you must save the members to a file or the registry, to be reloaded when the program is next run.
What is the code to be written in destructor to free the unused memory in c plus plus?
If memory is unused then it does not need to be freed. Unused memory is unallocated memory, and all unallocated memory belongs to the system.
In order to use memory you must first allocate it. To keep track of that allocation you must maintain a pointer to it, and must release that allocation when it is no longer required. Allocating memory you don't actually need is extremely wasteful, therefore it is always best to allocate memory as and when it is actually required, and release that allocation as soon as it is no longer required. If there's ever an occasion where allocated memory is "unused" then you must question why you allocated the memory in the first place.
As to what code to place in the destructor to release an allocation, you must first ascertain whether that memory belongs to the class or is shared with other instances of the same class. If the memory is shared, then, in the absence of a reference counting mechanism, no instance can own the memory -- it must be allocated outside of the class and released outside of the class. in this case, each instance of the class need only copy the pointer's value, not what it points to (a shallow copy).
For classes that own an allocation, you not only have to release that memory upon destruction, you must also ensure the copy constructor and assignment operator perform a deep copy of the memory. This means you cannot rely upon compiler generated constructors nor assignment, as they will only perform a member-wise copy (another term for shallow copy).
If you have a mutator (setter), a deep copy must be performed there also. Both the assignment operator and the mutator must also check for self-references before releasing any existing allocations prior to making a deep-copy. In addition, any accessor (getter) must also return a deep-copy of any allocation in order to maintain encapsulation of the member pointer (if you return a shallow copy, there's always a danger the memory will be released from outside of the class, which is never a good thing).
The following example demonstrates a class that owns allocated memory. For the sake of simplicity, the memory simply contains an integer, but all allocations are treated the same regardless of the type or complexity. Simple replace all occurrences of 'int' with whatever class of object you intend to use.
Note that if the object being pointed at must be guaranteed to exist at all times, then it is better (safer) to use an embedded member object (with static allocation) instead of using dynamic allocation (in other words, use an int variable rather than a pointer to int). However, the following example does NOT guarantee the object's existence, but must take ownership of any allocation passed to it. Hence the prevalent use of deep-copy and tests for NULL and self-references. Note also the use of the tertiary conditional operator (?:) to test for NULL pointers.
class foo
{
public: // construction and assignment.
foo(void);
foo(const int& i);
foo(const foo& f);
foo& operator=(const foo& f);
~foo(void);
public: // mutator.
void set_data(int* d);
public: // accessor.
int* get_data() const;
private: // member.
int * m_data;
};
// Default constructor. Initialises object to NULL.
foo::foo(void):m_data(NULL){}
// Overloaded constructor. Initialises object by reference.
foo::foo(const int& i):m_data(new int(i)){}
Note that although the default and overloaded constructor could be combined into a single default constructor with a default by-value parameter [foo::foo(const int i=0);] this means the allocation must be guaranteed to exist and therefore a member pointer would be superfluous (an embedded member object would be safer). The only suitable alternative would be to pass a pointer with a default of NULL, as shown here:
// Combined default and overloaded constructor:
foo::foo(int* p=NULL):m_data(p?new int(*p):NULL){}
The remainder of the class implementation follows:
// Copy constructor. Deep-copy.
foo::foo(const foo& f):m_data(f.m_data?new int(*f.m_data):NULL){}
// Assignment operator overload. Deep copy.
foo& foo::operator=(const foo& f)
{
// Check for self-reference.
if( this != &f )
{
// Release the existing allocation and deep-copy.
if( m_data )
delete( m_data );
m_data=f.m_data?new int(*f.m_data):NULL;
}
// Return this instance by reference.
return( *this );
}
// The all-important destructor:
foo::~foo( void )
{
// Release allocation.
if( m_data )
delete( m_data );
}
// Mutator.
void foo::set_data(int* d)
{
// Check for self-reference.
if( d != m_data )
{
// Release and deep-copy.
if( m_data )
delete( m_data );
m_data = d?new int(*d):NULL;
}
}
// Accessor: returns a deep copy (caller must release the copy).
int* foo::get_data(void) const
{
return(m_data?new int(*m_data):NULL);
}
Code in c plus plus of phonebook using linked list?
#include<iostream>
#include<list>
class person
{
std::string m_name;
std:string m_phone;
public:
const char* get_name()const{return( name.c_str() );}
const char* get_phone()const{return( phone.c_str() );}
person(std::string m_name, std::string m_phone) : m_name(name), m_phone(phone) {}
};
int main()
{
std::list<entry*> phonebook;
person* p = new entry("Joe Bloggs","01234 555 6789");
phonebook.push_back(p);
p = new person("Ann Other", "01234 555 9876");
phonebook.push_back(p);
p = new person("Some One", "01234 555 8769");
// and so on...
return(0);
}
How do you delete element from a stack?
Stacks are typically implemented as singly-linked lists, where new elements are pushed onto the tail of the list. Thus only the tail needs to be maintained. To remove an element you simply pop the tail element. Note that some implementations only maintain the head element, thus elements are pushed onto or popped from the head instead.
What is the difference between directives and instructions?
Directives are a signal to the pre-preprocessor that the following code must be modified prior to compilation. For instance, the #include directive tells the pre-processor that the specified file's contents must be pre-processed and then inserted at that point in the current file. The file itself should include compiler directives to prevent the file being included more than once (inclusion guards). Any line that has a leading pound symbol (#) in the first column can be considered a directive, but "using namespace..." is also a directive.
"Instructions" is an ambiguous term that we do not use in C++. Used literally, it could mean inline assembly instructions but some people might use the term to mean any C++ command. The correct terms for these are keywords and reserved words.
How do you write a cpp program to multiply two numbers?
#include<iostream>
int main()
{
std::cout << "Enter two numbers: ";
double a, b;
std::cin >> a >> b; // note: error handling omitted for brevity!
std::cout <<"The product of " << a << " and " << b << " is " << a*b << '\n';
}
What is the difference between the public and default access specifiers?
Here is a brief explanation of the access modifiers allowed in Java: default: objects are visible from within their own class, or any other class in the same package. public: objects are visible from within their own class, or from any other class within the project (regardless of which package it is in). protected: objects are visible from within their own class or any other class within the same package; objects are also visible from any class that is a subclass. private: objects are only visible from within from within their own class. It is important to note that all but the default access modifier need to be specified. For example: public String foo; (public) protected String foo; (protected) private String foo; (private) String foo; (default) For more information on this topic, you can read this page: http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
Answer:
Public access modifier Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package. public classes, methods, and fields can be accessed from everywhere. The only constraint is that a file with Java source code can only contain one public class whose name must also match with the filename. If it exists, this public class represents the application or the applet, in which case the public keyword is necessary to enable your Web browser or appletviewer to show the applet. You use public classes, methods, or fields only if you explicitly want to offer access to these entities and if this access cannot do any harm.
Default access modifier Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface. If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package. This access-level is convenient if you are creating packages. For example, a geometry package that contains Square and Tiling classes, may be easier and cleaner to implement if the coordinates of the upper-left corner of a Square are directly available to the Tiling class but not outside the geometry package.
How do you toggle case of string in c code. Example is TogGle will turn into tOGgLE?
#include<stdio.h> int main() { char str[100]; int i; printf("Please enter a string: "); // gets(str); // fgets is a better option over gets to read multiword string . fgets(str, 100, stdin); // Following can be added for extra precaution for '\n' character // if(str[length(str)-1] == '\n') str[strlen(str)-1]=NULL; for(i=0;str[i]!=NULL;i++) { if(str[i]>='A'&&str[i]<='Z') str[i]+=32; else if(str[i]>='a'&&str[i]<='z') str[i]-=32; } printf("String in toggle case is: %s",str); return 0; }
What is meant when you say you dereference a pointer variable?
When you dereference a pointer you are referring to the object being pointed at.
int* ptr = new int (42);
int& ref = *ptr;
You must be careful when you dereference pointers like this because ptr is volatile and could be deleted at any time. If ref is still in scope after ptr is released, ref will refer to invalid memory and thus invalidates your program. Moreover, if ptr falls from scope without releasing the memory it points to and ref remains in scope, there's no way to release the memory without invalidating ref which, again, invalidates your program. In order to be valid, references to dereferenced pointer values must be placed in a separate scope from the pointer and must fall from scope before the pointer falls from scope. Even if a reference falls from scope immediately after a pointer falls from scope, your program is still deemed invalid.
In some cases there is no need to hold a reference to a dereferenced pointer value, you can simply store the value by copying it to another variable.
int i = *ptr;
However, if the pointer is a complex object, keep in mind that this could invoke a cascade of copy constructors, which may impact performance.
The following code snippet shows all the major properties of a pointer: its own address, its value (the address being pointed to) and the indirect value (the dereferenced value).
std::cout << "Address: &ptr = 0x" << &ptr << std::endl;
std::cout << "Value: ptr = 0x" << ptr << std::endl;
std::cout << "Dereference: *ptr = " << *ptr << std::endl;
Write a c programme to perform Lagrange's interpolation formula?
#include<stdio.h> #include<conio.h> #include<math.h> void
main() { float
x[10],y[10],temp=1,f[10],sum,p; int
i,n,j,k=0,c; clrscr(); printf("\nhow many record you will be enter: "
); scanf("%d"
,&n); for
(i=0; i<n; i++) { printf("\n\nenter the value of x%d: "
,i); scanf("%f"
,&x[i]); printf("\n\nenter the value of f(x%d): "
,i); scanf("%f"
,&y[i]); } printf("\n\nEnter X for finding f(x): "
); scanf("%f"
,&p); for
(i=0;i<n;i++) { temp = 1; k = i; for
(j=0;j<n;j++) { if
(k==j) { continue
; } else
{ temp = temp * ((p-x[j])/(x[k]-x[j])); } } f[i]=y[i]*temp; } for
(i=0;i<n;i++) { sum = sum + f[i]; } printf("\n\n f(%.1f) = %f "
,p,sum); getch(); }
How do you access a base class method from a derived class in Cpp?
Use the scope resolution operator (::) to explicitly call the base class method. Note that the base class method must be protected or public in order for a derived class to access it. Private members are only accessible to the class itself and to friends of the class, regardless of whether the derivative uses public, protected or private inheritance.
It is quite normal for a base class to provide a "default" implementation for a virtual method for which a derived class may override. Although the derived class will generally provide its own implementation of the method, it may also call the base class method either before, during or after performing its own implementation.
The following shows minimal class declarations demonstrating a call to a protected base class method from a derived class override.
class base
{
protected:
// accessible to all instances of this class, its friends and its derivatives.
virtual void method(){
/* do something */
}
};
class derived : public base
{
public:
// full-accessible outside of class.
virtual void method(){
/* do something (or do nothing) */
base::method(); // call base class method.
/* do something else (or do nothing) */
}
};
You normally create a thread when you want to run a function in the background while processing other things.
How do you calculate execution time of an exe file?
Use a high-resolution timer such as the HPET (high performance event timer).
What is the C plus plus programs to implement the stack ADT using a singly linked list?
#include<iostream>
#include<time.h>
#include<forward_list>
int main()
{
// seed random number generator
srand ((unsigned) time(NULL));
// a forward_list is a singly-linked list
std::forward_list<int> stack;
// push 10 integers onto stack
for (int loop=0; loop<10; ++loop)
{
int num=rand();
std::cout<<"Pushing "<<num<<std::endl;
stack.push_front (num);
}
// pop all integers
while (!stack.empty())
{
std::cout<<"Popping "<<stack.front()<<std::endl;
stack.pop_front();
}
}
What is printf in c plus plus programming?
printf is a function that prints formatted text to the standard output stream (stdout). To make use of it in C++, you must include cstdio or any file that includes cstdio.
For more information, see related links.
What is the primary value in using virtual functions within C plus plus?
Virtual methods are member methods of a base class that can be overridden by derived classes. Classes that can act as base classes should contain all the functionality that is common to all their derived classes. However, the derived classes may need to alter that functionality in some way by overriding the methods in the base class.
While this is fine when we actually hold pointers or references to a derived object, what happens when we hold pointers or references to the base class of a derived object? We cannot call the overridden methods explicitly unless we expose the runtime class of the derived object, which would incur an unacceptable processing overhead.
Virtual methods allow us to get around this problem in a more elegant fashion. By declaring a method as virtual, calling the method implicitly on a base class will automatically and explicitly call the most-derived implementation in the class hierarchy. If no override exists, the base class method is called explicitly.
While this mechanism incurs a memory penalty in creating the v-table (virtual table), the bulk of that cost is paid with the first virtual method declared. Subsequent methods add very little overhead, so it is not uncommon for programmers to declare all methods virtual. However, if there is at least one virtual method declared, the class destructor must also be declared virtual. Thereafter, you should only declare other methods to be virtual if there is an actual need to do so. After all, there's no point in consuming more memory than is actually required.
Sometimes it is not possible for a base class to provide the implementation for a virtual method, In this case the method should be declared pure-virtual. The same rules apply as for virtual functions, however you can no longer instantiate objects from the base class itself -- it becomes an abstract class -- so you must derive from it and you must provide an implementation for all the pure-virtual methods (otherwise it becomes abstract itself).
Abstract classes will generally have few, if any, member variables, and all member methods will generally be declared as pure-virtual. Abstract classes are primarily intended to provide a common interface to their derivatives. The base class can still provide default implementations for pure-virtual methods, however they must be explicitly called. In some cases, a derived class will simply augment the default implementation, rather than override it completely.
Be aware that base classes that are common to derived classes that can be used by multiple inheritance classes will introduce ambiguities. The multiple inheritance class will inherit two or more instances of the common base class, and therefore must be called explicitly from the multiple inheritance class. However, it is possible to remove the ambiguity altogether, by declaring the common base class to be virtual in its immediate derivatives, in which case all derivatives share the same common base class when multiply inherited. Ideally, the common base class should have very little in the way of implementation, and few, if any, member variables.
What are risks of object oriented development?
There are no risks, as such. The point of object-oriented programming is to reduce the risks of invalidating data unintentionally. With a well-designed class system, there should be no risk whatsoever. With a badly-designed class system, the risks are as a great as those with structured or procedural programming.
A method that is automatically called when an instance of a class is created?
The constructor of a class is automatically called when an instance of the class is created (using new in C++). The constructor method has the same name as the class that it is a part of. Constructors have no type and do not return anything.
Similarly, the destructor is automatically called when the instance of the class is destroyed. The destructor is the same name as the class and is preceded by a tilde (~)
For example:
class Example
{
public:
Example() // Constructor
{
printf("Object created\n");
}
~Example() // Destructor
{
printf("Object destroyed\n")
} };
int main()
{
Example* x = new Example(); // Creates object, calls constructor
delete x; // Calls destructor, deletes object
return 0;
}
How do you concatenate a string?
v can concatenate two string by using a function like: select CONCAT( CONCAT('ename','e_mrks'),"name","marks" from student;
Can structured techniques and object-oriented techniques be mixed?
Yes, in fact, they are always mixed. You always write structured procedures (the main function, at least), that will control your objects. Objects can't work just by themselves. At least, that's how it is in C++.
How to check whether variable is allocated on stack or heap in CPP programmatically?
You can not check whether a variable (object) is allocated on the stack or heap in CPP programmatically.
If you are being passed the address of an object, you may not make any assumptions about how that object was allocated unless you are also passed information about that allocation. The "owner" or allocator of the object knows how that object was allocated. The "user" of the object does not know, unless told, and should not even care.
If you want to write code that transfers "ownership" of an object to another "owner", you may, but that new "owner" must be told how to manage the object.
It is possible to look at the address of the object, and infer locality based the value of that address, but that is extremely fragile, because it is implementation specific. Do not even consider it.
It IS possible to create a class that can track whether it was allocated on the stack or heap. To do so, you need to override the desired operater new() and operate delete() functions in your class, such that your class will be allocating instances of the class itself. Then you need a means to signal from the operator new() function back to the class instance that it was allocated via new (since operator new executes before the class constructor). One simple way to do this is to keep a global list of all the objects you've created for the class (via operator new); the class constructor can then lookup the this pointer in the list to see if it was allocated with new, and set a flag accordingly. In this case, operator delete() would need to remove items from the list.
If your program is multi-threaded, access to this global list would either need to be protected by a semaphore or the list could reside in thread-local storage.
What was the most important capability of C plus plus that C did not provide?
The most important capability is Object Oriented Programming (OOP) principals, which necessitated the inclusion of classes. That was the main reason Bjarne Stroustrup developed C++ in the first place (indeed, C++ was originally called 'C with Classes').